【问题标题】:pandas resample interpolate is producing NaNspandas resample interpolate 正在产生 NaN
【发布时间】:2018-04-19 07:04:42
【问题描述】:

修改自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
....

但如果我将重采样更改为 '5s',它只会产生 NaN:

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
....

为什么?

【问题讨论】:

  • 刚刚遇到这个问题here - 如果resample 给您留下一些 数据(不是所有的NaN),它会变得更加混乱。

标签: python pandas interpolation


【解决方案1】:

选项 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')


选项 2A
如果您愿意放弃准确性,可以ffill 限制为1

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


选项 2B
bfill 相同

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


选项 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')

【讨论】:

  • 真的有那么复杂吗?最终我想在之后再次对其进行下采样,但我不能只对原始非均匀采样的数据进行下采样,否则它不会计算样本之间的信号
  • 我看不到用当前的 api 更简洁地做到这一点的方法。我可能是错的,但这是我能做的最好的。
  • @endolith 但是,我添加了一些您可能喜欢的选项。
  • @JamesAdams 很高兴它帮助了你
  • 哇,这太有帮助了。寻找这样的东西很久了。谢谢
【解决方案2】:

对我来说,我必须添加 astype() 才能使其工作,否则它会产生 Nan 值:

oidx = s.index
nidx = pd.date_range(oidx.min(), oidx.max(), freq='2min')
res=s.reindex(oidx.union(nidx)).astype(float).interpolate('index').reindex(nidx)

【讨论】:

    猜你喜欢
    • 2012-08-14
    • 2018-11-06
    • 2016-01-26
    • 2016-09-20
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    相关资源
    最近更新 更多