python - Pandas - 在日内数据中广播每日数据

标签 python pandas dataframe

我有一个每日数据帧和一个日内数据帧,我想通过每天广播每日数据来添加这两个帧。下面的最小示例:

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/

相关文章:

python - 安装在Google Colab中的Google云端硬盘中的相对路径

dataframe - Julia:将 DataFrame 中的列类型从 Integer 转换为 Float64

python - 如何在 Django 模型中轻松创建计算字段?

Python 3.5 Pandas 和 MongoDB -json_normalize : raise TypeError ("data argument can' t be an iterator")

r - 多行到单个单元格空间分隔 Pandas 中的值,分组依据

python - Pandas:高效地将一行拆分为多行

python - 使用python访问函数内部的字典

python - 按一列或另一列对 pandas 数据框进行分组

python - Tkinter 顶级小部件不显示 - python

python - 填充数组的最快方法?