我有两个不同的时间序列,不同的大小。我想将时间序列(1)的NaN值替换为时间序列(2)同一个月的最后一个可用值。有功能可以做到这一点吗? 这是我的时间范围:
timerange = pd.date_range('1/1/1', periods = 9, freq = 'D')
d1_t
是我的第一个时间序列:
d1_t = pd.Series(np.random.randn(len(timerange)), timerange)
我要添加一个Na:
d1_t['2001-01-03'] = np.nan
我的第二个time_series是d2_t
:
d2_t = pd.Series(np.random.randn(len(timerange)), timerange)
我希望将当前具有NaN值的d1_t['2001-01-03']
替换为d2_t['2001-01-02']
答案 0 :(得分:1)
使用方法fillna()
d1_t = d1_t.fillna(d2_t)
这将填充当天的数据。
我想念OP希望每天换一次数据来代替。为此,请参见@ansev的答案。
答案 1 :(得分:1)
使用Series.fillna
+ Series.shift
。
仅当系列的索引完全相同时:
d1_t=d1_t.fillna(d2_t.shift())
print(d1_t)
2001-01-01 0.268759
2001-01-02 -0.064546
2001-01-03 -1.567730
2001-01-04 -0.770255
2001-01-05 0.479366
2001-01-06 -0.305752
2001-01-07 1.489243
2001-01-08 0.397007
2001-01-09 0.025405
Freq: D, dtype: float64