You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用DateIndex将日度DataFrame重采样为小时级并填充当日值

问题:日度DataFrame重采样为小时级并填充当日价格值

现有日度DataFrame:

date,Prices
2018-01-01,  45.338
2018-01-02,  39.955

需求:将其转换为小时级数据,当日每小时均使用该日的Prices值,最终得到包含每日24小时记录的DataFrame。

已通过以下代码读取数据:

dfr     =  pd.read_csv('input.csv', parse_dates=True,index_col=0,
                       infer_datetime_format=True,
                       cache_dates=True)

尝试两种方法均未达到预期:

  1. 调用DatetimeIndex的resample方法报错:
new_df = dfr.index.resample("H").ffill().rename(
     {"Prices"}, axis=1
 )

报错信息:

AttributeError: 'DatetimeIndex' object has no attribute 'resample'
  1. 使用resample+mean仅保留当日0点数值,其余小时为NaN:
new_dfr = dfr.resample(rule='H')['Prices'].mean()

正确实现方法

方法1:resample + 前向填充(ffill)

resample是DataFrame/Series的方法,而非DatetimeIndex的方法。重采样为小时级后,用ffill()将当日0点的价格填充到该日所有小时行:

new_dfr = dfr.resample('H').ffill()

方法2:resample + pad(与ffill等价)

pad()和ffill()功能完全一致,都是向前填充缺失值:

new_dfr = dfr.resample('H').pad()

方法3:手动生成小时索引 + 重索引填充

先构造完整的小时级时间序列,再通过reindex对齐并填充:

# 生成包含所有目标小时的时间索引
hourly_index = pd.date_range(
    start=dfr.index.min(), 
    end=dfr.index.max() + pd.Timedelta(hours=23), 
    freq='H'
)
# 重索引并前向填充价格值
new_dfr = dfr.reindex(hourly_index).ffill()

以上三种方法均可得到每日24小时均填充对应日价格的DataFrame。


内容的提问来源于stack exchange,提问作者diedro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 09:20:12