将每日值合并到日内DataFrame中

时间:2016-12-21 20:19:53

标签: python datetime pandas dataframe

假设我有两个DataFramesintraday每分钟有一行,而daily每天有一行。

如何添加intraday['some_val']列,其中some_val取自daily['some_val']intraday.index值(日期分量)等于daily.index值的行JPanel (日期组成部分)?

1 个答案:

答案 0 :(得分:2)

鉴于以下设置,

intraday = pd.DataFrame(index=pd.date_range('2016-01-01', '2016-01-07', freq='T'))
daily = pd.DataFrame(index=pd.date_range('2016-01-01', '2016-01-07', freq='D'))
daily['some_val'] = np.arange(daily.shape[0])

您可以从两个索引的日期组件创建一个列,并在该列上合并

daily['date'] = daily.index.date
intraday['date'] = intraday.index.date    
daily.merge(intraday)
            date  some_val
0     2016-01-01         0
1     2016-01-01         0
2     2016-01-01         0
3     2016-01-01         0
4     2016-01-01         0
...          ...       ...
8636  2016-01-06         5
8637  2016-01-06         5
8638  2016-01-06         5
8639  2016-01-06         5
8640  2016-01-07         6

或者,您可以利用自动索引对齐,并使用fillna

intraday['some_val'] = daily['some_val']
intraday.fillna(method='ffill', downcast='infer')
                     some_val
2016-01-01 00:00:00         0
2016-01-01 00:01:00         0
2016-01-01 00:02:00         0
2016-01-01 00:03:00         0
2016-01-01 00:04:00         0
...                       ...
2016-01-06 23:56:00         5
2016-01-06 23:57:00         5
2016-01-06 23:58:00         5
2016-01-06 23:59:00         5
2016-01-07 00:00:00         6

请注意,这只适用于daily索引的时间部分为00:00的情况。