熊猫系列重新采样+内插可得出NaN

时间:2018-09-20 18:42:46

标签: python-3.x pandas

x是在DateTimeIndex上的一连串的float64数字

x.head(20)看起来像这样:

Timestamp
2018-05-03 15:05:31.864    1.799104
2018-05-03 15:05:31.993    1.080555
2018-05-03 15:05:32.145    1.374885
2018-05-03 15:05:32.963    1.264249
2018-05-03 15:05:33.529    1.251358
2018-05-03 15:05:33.938    1.199366
2018-05-03 15:05:34.378    1.201764
2018-05-03 15:05:34.496    1.267969
2018-05-03 15:05:34.895    1.251358
2018-05-03 15:05:36.572    1.313922
2018-05-03 15:05:37.562    1.270770
2018-05-03 15:05:38.013    1.230315
2018-05-03 15:05:38.166    1.185131
2018-05-03 15:05:38.285    1.150098
2018-05-03 15:05:39.555    1.122180
2018-05-03 15:05:39.698    1.094660
2018-05-03 15:05:40.815    1.084887
2018-05-03 15:05:41.700    1.068585
2018-05-03 15:05:41.993    1.071981
2018-05-03 15:05:42.139    1.084344
Name: C2:37:A3:40:10:60_s, dtype: float64

我想做的是对系列重新采样并内插到100ms的周期。这是我尝试过的:

y = x.resample("100ms").interpolate("linear")

它根本并没有实现我的预期。

首先,y包含1700个条目中的大约100个NaN。插值法不应该照顾NaN吗?

我继续绘制了原始的x系列和重新采样的'y'系列。plotted x series (left), y series(right)

我在做什么错?我真的只是想获得一个很好且平滑的序列,每100ms就有一个值,并在必要时进行线性插值。基本上将左图变成右图:

what I have (left), what I want (right)

我曾经直接通过scipy.interpolate.interp1d进行此操作,但是希望直接在熊猫中使用一些不那么麻烦的东西。

1 个答案:

答案 0 :(得分:1)

IIUC:

您想对现有索引与重采样索引的并集进行插值。

idx = pd.date_range(x.first_valid_index(), x.last_valid_index(), freq='100ms')

这是获取索引的一种可爱方式

idx = x.asfreq('100ms').index

如果您想要'100ms'的圆形单位

idx = idx.floor('100ms')

  1. 具有联合索引的重新索引
  2. 'index'进行插值。这将基于索引值之间的间隔为线性。
  3. 使用减少后的'100ms'重新建立索引

y = x.reindex(x.index.union(idx)).interpolate('index').reindex(idx)


y

Timestamp
2018-05-03 15:05:31.864    1.799104
2018-05-03 15:05:31.964    1.242089
2018-05-03 15:05:32.064    1.218038
2018-05-03 15:05:32.164    1.372315
2018-05-03 15:05:32.264    1.358790
2018-05-03 15:05:32.364    1.345265
2018-05-03 15:05:32.464    1.331740
2018-05-03 15:05:32.564    1.318214
2018-05-03 15:05:32.664    1.304689
2018-05-03 15:05:32.764    1.291164
                             ...   
2018-05-03 15:05:41.164    1.078458
2018-05-03 15:05:41.264    1.076616
2018-05-03 15:05:41.364    1.074774
2018-05-03 15:05:41.464    1.072932
2018-05-03 15:05:41.564    1.071090
2018-05-03 15:05:41.664    1.069248
2018-05-03 15:05:41.764    1.069327
2018-05-03 15:05:41.864    1.070486
2018-05-03 15:05:41.964    1.071645
2018-05-03 15:05:42.064    1.077993
Freq: 100L, Name: C2, Length: 103, dtype: float64
相关问题