【问题标题】:Interpolating from a pandas DataFrame or Series to a new DatetimeIndex从 pandas DataFrame 或 Series 插值到新的 DatetimeIndex
【发布时间】:2020-01-04 11:57:46
【问题描述】:

假设我有一个关于熊猫的每小时系列,假设来源是常规的,但它是有缺陷的。如果我想将其插入 15 分钟,pandas API 提供resample(15min).interpolate('cubic')。它插值到新的时间并提供对插值限制的一些控制。样条线有助于完善系列并填补小空白。具体来说:

tndx = pd.date_range(start="2019-01-01",end="2019-01-10",freq="H")    
tnum = np.arange(0.,len(tndx))
signal = np.cos(tnum*2.*np.pi/24.)

signal[80:85] = np.nan   # too wide a gap
signal[160:168:2] = np.nan   # these can be interpolated

df = pd.DataFrame({"signal":signal},index=tndx)    
df1= df.resample('15min').interpolate('cubic',limit=9)

现在假设我有一个不规则的日期时间索引。在下面的例子中,第一次是常规时间点,第二次是大间隙,最后一次是穿插的短暂间隙。

tndx2 = pd.DatetimeIndex('2019-01-04 00:00','2019-01-04 10:17','2019-01-07 16:00')

如何从原始系列(每小时)插入到这个不规则的时间系列?

是构建包含原始数据和目标数据的系列的唯一选择吗?我该怎么做?实现对独立不规则索引进行插值并施加间隙限制的目标最经济的方法是什么?

【问题讨论】:

  • 您可以将原始数据resample 转换为1s,然后使用reindex,或者对插值后的数据进行索引切片。
  • 谢谢。我认为这可以工作,如果您知道“最小公分母”(在这里说 1 分钟而不是 1 秒),它可能会完成这项工作。但它对我的上下文来说很重,特别是如果插值器本身很昂贵。跨度>

标签: python pandas time-series interpolation


【解决方案1】:

如果时间戳不规则,首先将日期时间设置为索引,然后可以使用interpolate方法来indexdf1= df.resample('15min').interpolate('index')

你可以在这里找到更多信息https://pandas.pydata.org/pandas-docs/version/0.16.2/generated/pandas.DataFrame.interpolate.html

【讨论】:

  • 我正在尝试从源系列插入到目标系列或索引(我没有更清楚地说明这一点是不好的)。除非你暗示有很多额外的步骤,比如结合源和目标,否则我看不到你在解决我的问题。另外,在更微妙的层面上,我不知道interpolate('index') 的底层算法是什么——我假设是线性的?
【解决方案2】:

这是 pandas 插值 API 中的一个示例解决方案,它似乎没有办法使用源系列中的横坐标和值来插值到目标索引提供的新时间,作为单独的数据结构。此方法通过将目标附加到源来解决此问题。该方法利用了df.interpolatelimit 参数,它可以使用该API 中的任何插值算法,但它并不完美,因为限制取决于值的数量以及是否有很多目标点在一块 NaN 中,它们也会被计算在内。

tndx = pd.date_range(start="2019-01-01",end="2019-01-10",freq="H")    
tnum = np.arange(0.,len(tndx))
signal = np.cos(tnum*2.*np.pi/24.)

signal[80:85] = np.nan
signal[160:168:2] = np.nan
df = pd.DataFrame({"signal":signal},index=tndx)

# Express the destination times as a dataframe and append to the source
tndx2 = pd.DatetimeIndex(['2019-01-04 00:00','2019-01-04 10:17','2019-01-07 16:00'])
df2 = pd.DataFrame( {"signal": [np.nan,np.nan,np.nan]} , index = tndx2)
big_df = df.append(df2,sort=True)  

# At this point there are duplicates with NaN values at the bottom of the DataFrame
# representing the destination points. If these are surrounded by lots of NaNs in the source frame
# and we want the limit argument to work in the call to interpolate, the frame has to be sorted and duplicates removed.     
big_df = big_df.loc[~big_df.index.duplicated(keep='first')].sort_index(axis=0,level=0)

# Extract at destination locations
interpolated = big_df.interpolate(method='cubic',limit=3).loc[tndx2]

【讨论】:

    猜你喜欢
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    • 2017-08-08
    • 2022-01-23
    相关资源
    最近更新 更多