2013-09-23 81 views
5

我有一组在常规时间测量的值。你说:在熊猫中插入一个时间序列到另一个时间序列

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) 

,另一组的多个任意时间,例如,(在现实中这些时间是不是正规的顺序)

ts_rng = pd.date_range('2013-01-01 01:11:21', periods=7, freq='87Min') 
ts = pd.Series(index=ts_rng) 

我想知道在时间内插数据的值在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) 

但我感觉熊猫在resamplereindex等地方这个功能,但我不能完全得到它。

回答

7

您可以连接两个时间序列并按索引排序。由于在第二个系列的值是NaN可以interpolate以及刚刚选出代表从第二系列点的值:

pd.concat([data, ts]).sort_index().interpolate().reindex(ts.index) 

pd.concat([data, ts]).sort_index().interpolate()[ts.index] 
+3

您需要使用方法=“值”的主要论点在插值得到同样的答案在numpy pd.concat([data,ts])。sort_index()。interpolate(method ='values')[ts.index] – elfnor

+2

注意显示在ts和数据中的索引 – tschm

4

假设你想评价时间序列ts在不同的datetime_index上。这个索引和ts的索引可能会重叠。我建议使用以下groupby技巧。这基本上摆脱了可疑的双重邮票。然后我向前插,但随时申请更看中的方法

def interpolate(ts, datetime_index): 
    x = pd.concat([ts, pd.TimeSeries(index=datetime_index)]) 
    return x.groupby(x.index).first().sort_index().fillna(method="ffill")[datetime_index] 
0

这里有一个干净的衬垫:

ts = np.interp(ts_rng.asi8 ,data.index.asi8, data[0])