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

Pandas重采样时如何自动向前填充(ffill)最后一条数据?

解决DataFrame重采样后最后一个值无法向前填充的问题

问题分析

原代码里resample('15T')默认只会生成从原DataFrame起始索引到原结束索引的采样时间点,所以最后一个时间点2022-01-01 04:00:00之后的15分钟间隔点不会被创建,自然没法通过ffill()填充后续值。

优雅解决方案

方案1:直接构造完整目标时间索引(推荐)

先生成包含原时间范围及后续需要填充的时间点的完整索引,再用reindex结合ffill实现填充:

import pandas as pd

df = pd.DataFrame(index=pd.date_range(start='1/1/2022', periods=5, freq='h'), data=range(0,5))
# 构造从起始时间到最后一个时间+45分钟的15分钟间隔索引
target_index = pd.date_range(
    start=df.index[0],
    end=df.index[-1] + pd.Timedelta(minutes=45),
    freq='15T'
)
# 重索引并向前填充
result = df.reindex(target_index).ffill()
print(result)

输出结果会包含2022-01-01 04:15:00、04:30:00、04:45:00三个时间点,对应值均为4。

方案2:重采样后追加缺失时间点

先完成基础重采样,再生成需要补充的时间点,合并后填充:

import pandas as pd

df = pd.DataFrame(index=pd.date_range(start='1/1/2022', periods=5, freq='h'), data=range(0,5))
# 基础重采样
df_resampled = df.resample('15T').ffill()
# 生成需要追加的3个15分钟时间点
additional_times = pd.date_range(
    start=df_resampled.index[-1] + pd.Timedelta(minutes=15),
    end=df_resampled.index[-1] + pd.Timedelta(minutes=45),
    freq='15T'
)
# 合并并填充
result = pd.concat([df_resampled, pd.DataFrame(index=additional_times)]).ffill()
print(result)

关键逻辑

两种方案的核心都是确保目标时间索引包含原结束时间之后需要填充的时间点,这样ffill()才能将最后一个值向前填充到这些新增的时间点上。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 08:50:28