我有一个每日数据帧和一个日内数据帧,我想通过每天广播每日数据来添加这两个帧。下面的最小示例:
import numpy as np
import pandas as pd
cols = ['A', 'B']
days = pd.date_range('1/1/2000', periods=2, freq='D')
df_d = pd.DataFrame(np.arange(4).reshape((2, 2)), index=days, columns=cols)
hours = pd.date_range('1/1/2000', periods=4, freq='12H')
df_h = pd.DataFrame(np.arange(8).reshape((4, 2)), index=hours, columns=cols)
target = pd.DataFrame([[0, 2],[2, 4],[6, 8],[8, 10]], index=hours, columns=cols)
>>> df_d
A B
2000-01-01 0 1
2000-01-02 2 3
>>> df_h
A B
2000-01-01 00:00:00 0 1
2000-01-01 12:00:00 2 3
2000-01-02 00:00:00 4 5
2000-01-02 12:00:00 6 7
>>> target
A B
2000-01-01 00:00:00 0 2
2000-01-01 12:00:00 2 4
2000-01-02 00:00:00 6 8
2000-01-02 12:00:00 8 10
因此,我希望以稳健的方式执行 target = df_h "+"df_d
,因为日内时间戳可能会发生变化并且数据中可能存在 NaN。我尝试将 df_d
重新索引为 hours
,然后向前填充,但这本质上不尊重每日边界,并且很容易丢失数据。
最佳答案
您可以使用.add
标准化df_h
的索引后:
i = df_h.index
df_h.set_index(i.floor('D')).add(df_d, fill_value=0).set_index(i)
A B
2000-01-01 00:00:00 0 2
2000-01-01 12:00:00 2 4
2000-01-02 00:00:00 6 8
2000-01-02 12:00:00 8 10
关于python - Pandas - 在日内数据中广播每日数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65613092/