elf*_*nor 6 python numpy pandas
我有一组定期测量的值.说:
import pandas as pd
import numpy as np
rng = pd.date_range('2013-01-01', periods=12, freq='H')
data = pd.Series(np.random.randn(len(rng)), index=rng)
Run Code Online (Sandbox Code Playgroud)
而另一组更随意的时间,例如,(实际上这些时间不是常规序列)
ts_rng = pd.date_range('2013-01-01 01:11:21', periods=7, freq='87Min')
ts = pd.Series(index=ts_rng)
Run Code Online (Sandbox Code Playgroud)
我想知道ts中时间插值的数据的值.
我可以在numpy中做到这一点:
x = np.asarray(ts_rng,dtype=np.float64)
xp = np.asarray(data.index,dtype=np.float64)
fp = np.asarray(data)
ts[:] = np.interp(x,xp,fp)
Run Code Online (Sandbox Code Playgroud)
但是我觉得熊猫在某处有这种功能 resample,reindex但是我不能完全理解它.
您可以连接两个时间序列并按索引排序.由于第二个系列中的值是NaN可以的interpolate,因此只需选择代表第二个系列中的点的值:
pd.concat([data, ts]).sort_index().interpolate().reindex(ts.index)
Run Code Online (Sandbox Code Playgroud)
要么
pd.concat([data, ts]).sort_index().interpolate()[ts.index]
Run Code Online (Sandbox Code Playgroud)
假设您想在不同的datetime_index上评估时间序列ts.该索引和ts的索引可能重叠.我建议使用以下groupby技巧.这基本上摆脱了可疑的双重邮票.然后我转发插值但随意应用更多花哨的方法
def interpolate(ts, datetime_index):
x = pd.concat([ts, pd.Series(index=datetime_index)])
return x.groupby(x.index).first().sort_index().fillna(method="ffill")[datetime_index]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5649 次 |
| 最近记录: |