【问题标题】:Pandas Series resample + interpolate gives NaNsPandas 系列重采样 + 插值给出 NaN
【发布时间】:2019-02-25 03:11:43
【问题描述】:

x 是 DateTimeIndex 上 float64 数字的 pandas 系列

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

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

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

它根本没有达到我的预期。

首先,y 在 1700 个条目中包含大约 100 个 NaN。插值不应该处理 NaN 吗?

我继续绘制了原始的x 系列和重新采样的“y”系列。

我做错了什么?我真的只是想得到一个漂亮而平滑的系列,每 100 毫秒有一个值,在必要的地方线性插值。基本上把左图变成右图:

我以前直接用scipy.interpolate.interp1d 做这件事,但希望直接在 pandas 中使用一些不那么麻烦的东西。

【问题讨论】:

    标签: python-3.x pandas


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      • 2022-01-20
      • 2017-06-03
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多