使用另一个时间序列的索引重新采样时间序列

piR*_*red 12 python indexing time-series resampling pandas

我有2个数据帧具有相同的列但不同的日期时间索引.我想重新对其中一个进行重新采样,以使用另一个的索引,并在另一个没有数据的索引中的任何日期转发数据.

import pandas as pd
import numpy as np
from datetime import datetime as dt

a_values = np.random.randn(4, 4)
a_index = [dt(2012, 3, 16), dt(2012, 3, 19), dt(2012, 3, 20), dt(2012, 3, 21)]
a = pd.DataFrame(data=a_values, index=a_index)

b_values = np.trunc(np.random.randn(3, 4) * 1000)
b_index = [dt(2012, 3, 16), dt(2012, 3, 19), dt(2012, 3, 21)]
b = pd.DataFrame(data=b_values, index=b_index)

c_insert = a.ix['2012-03-20']
c = b.append(c_insert).sort()
c.ix['2012-03-20'] = c.ix['2012-03-19']
Run Code Online (Sandbox Code Playgroud)

'a'表示其索引我想用作重采样参考的数据帧.'b'表示我想重新采样和转发填充数据的数据帧.'c'表示我想要的结果.

请注意,'b'缺少'a'中存在的'2012-03-20'索引.'c'用索引'2012-03-19'的'b'列中的数据填充索引'2012-03-20'的列

pandas是否具有执行此操作的功能.

提前致谢.

PIR

Dan*_*lan 11

要通过参考索引重新采样,请使用reindex.

In [11]: b.reindex(a.index, method='ffill')
Out[11]: 
               0     1     2     3
2012-03-16  -926  -625   736   457
2012-03-19 -1024   742   732 -1020
2012-03-20 -1024   742   732 -1020
2012-03-21  1090 -1163  1652   -94
Run Code Online (Sandbox Code Playgroud)

  • 你也可以使用:`b.reindex_like(a,method ='ffill')`. (4认同)