代码之家  ›  专栏  ›  技术社区  ›  Mykola Zotko

重采样数据帧和插值返回NaN[重复]

  •  0
  • Mykola Zotko  · 技术社区  · 4 年前

    this example

    import io
    import pandas as pd
    import matplotlib.pyplot as plt
    
    data = io.StringIO('''\
    Values
    1992-08-27 07:46:48,1
    1992-08-27 08:00:48,2
    1992-08-27 08:33:48,4
    1992-08-27 08:43:48,3
    1992-08-27 08:48:48,1
    1992-08-27 08:51:48,5
    1992-08-27 08:53:48,4
    1992-08-27 08:56:48,2
    1992-08-27 09:03:48,1
    ''')
    s = pd.read_csv(data, squeeze=True)
    s.index = pd.to_datetime(s.index)
    
    res = s.resample('4s').interpolate('linear')
    print(res)
    plt.plot(res, '.-')
    plt.plot(s, 'o')
    plt.grid(True)
    

    1992-08-27 07:46:48    1.000000
    1992-08-27 07:46:52    1.004762
    1992-08-27 07:46:56    1.009524
    1992-08-27 07:47:00    1.014286
    1992-08-27 07:47:04    1.019048
    1992-08-27 07:47:08    1.023810
    1992-08-27 07:47:12    1.028571
    ....
    

    interpolated values

    但如果我把重采样改成 '5s'

    1992-08-27 07:46:45   NaN
    1992-08-27 07:46:50   NaN
    1992-08-27 07:46:55   NaN
    1992-08-27 07:47:00   NaN
    1992-08-27 07:47:05   NaN
    1992-08-27 07:47:10   NaN
    1992-08-27 07:47:15   NaN
    ....
    

    为什么?

    0 回复  |  直到 7 年前
        1
  •  19
  •   piRSquared    7 年前

    方案1
    '4s' 与现有索引完全一致。当你 resample ,则可以从旧序列中获得表示,并可以进行插值。您要做的是创建一个索引,它是旧索引与新索引的并集。然后使用新索引进行插值和重新索引。

    oidx = s.index
    nidx = pd.date_range(oidx.min(), oidx.max(), freq='5s')
    res = s.reindex(oidx.union(nidx)).interpolate('index').reindex(nidx)
    res.plot(style='.-')
    s.plot(style='o')
    

    enter image description here


    方案2A
    如果你愿意放弃准确性,你可以 ffill 限制为 1

    res = s.resample('5s').ffill(limit=1).interpolate()
    res.plot(style='.-')
    s.plot(style='o')
    

    enter image description here



    bfill

    res = s.resample('5s').bfill(limit=1).interpolate()
    res.plot(style='.-')
    s.plot(style='o')
    

    enter image description here


    方案3
    中等复杂度和准确性

    nidx = pd.date_range(oidx.min(), oidx.max(), freq='5s')
    res = s.reindex(nidx, method='nearest', limit=1).interpolate()
    res.plot(style='.-')
    s.plot(style='o')
    

    enter image description here