
本文介绍如何基于 pandas 对具有不同提交时间的分组数据(如 sku-location 组合)执行精细化前向填充(forward fill),确保每个“提交月”覆盖其后所有未提交月份,从而构建完整、连续的月度预测数据集。
本文介绍如何基于 pandas 对具有不同提交时间的分组数据(如 sku-location 组合)执行精细化前向填充(forward fill),确保每个“提交月”覆盖其后所有未提交月份,从而构建完整、连续的月度预测数据集。
在供应链预测、销售计划或财务滚动预测等场景中,原始数据常以“快照式提交”形式存在——即某 SKU 在某个地点仅在特定月份(如 Jan-2023、Apr-2023)提交一次预测,但业务要求后续所有月份(直至当前月,如 Dec-2023)均需有对应预测值。此时,简单全局 ffill() 无法满足需求,因为需按逻辑分组(如 sku + location)独立前向填充,并将每个历史提交月的数据“广播”至其生效区间内的所有目标月份。
核心思路是:将数据结构从“长格式”转为“宽格式—时间索引—前向填充—再压平”的三步范式,而非直接在原始 DataFrame 上调用 groupby().ffill()。这是因为原数据中同一 submissionmonth 下已包含多个 forecastmonth(如 Jan-2023 提交了 Jan–Apr 四个月的预测),我们需要让每个 submissionmonth 成为一个独立的时间行,再沿时间轴向前填充整行数据(即整套 forecastmonth→cost 映射),最后展开还原。
以下是完整可执行代码(含关键注释与健壮性处理):
import pandas as pd
# 原始输入数据(已定义)
input_data = pd.DataFrame([
{"submissionmonth": "Jan-2023", "sku": "A1", "location": "sup1", "forecastmonth": "Jan-2023", "cost": 100},
{"submissionmonth": "Jan-2023", "sku": "A1", "location": "sup1", "forecastmonth": "Feb-2023", "cost": 105},
{"submissionmonth": "Jan-2023", "sku": "A1", "location": "sup1", "forecastmonth": "Mar-2023", "cost": 108},
{"submissionmonth": "Jan-2023", "sku": "A1", "location": "sup1", "forecastmonth": "Apr-2023", "cost": 106},
{"submissionmonth": "Apr-2023", "sku": "A1", "location": "sup1", "forecastmonth": "Apr-2023", "cost": 101},
{"submissionmonth": "Apr-2023", "sku": "A1", "location": "sup1", "forecastmonth": "May-2023", "cost": 102},
{"submissionmonth": "Apr-2023", "sku": "A1", "location": "sup1", "forecastmonth": "Jun-2023", "cost": 109},
{"submissionmonth": "Apr-2023", "sku": "A1", "location": "sup1", "forecastmonth": "Jul-2023", "cost": 104},
{"submissionmonth": "Oct-2023", "sku": "A2", "location": "sup2", "forecastmonth": "Oct-2023", "cost": 101},
{"submissionmonth": "Oct-2023", "sku": "A2", "location": "sup2", "forecastmonth": "Nov-2023", "cost": 102},
{"submissionmonth": "Oct-2023", "sku": "A2", "location": "sup2", "forecastmonth": "Dec-2023", "cost": 109},
{"submissionmonth": "Oct-2023", "sku": "A2", "location": "sup2", "forecastmonth": "Jan-2024", "cost": 104},
])
# 步骤 1:提取所有唯一 submissionmonth 并转为 datetime,确定完整时间范围
submission_months = pd.to_datetime(input_data["submissionmonth"], format="%b-%Y")
min_month, max_month = submission_months.min(), submission_months.max()
# 注意:此处使用 'M'(月末)频率,但显示仍为 "%b-%Y" 格式;若需包含当前月(Dec-2023)且原数据未覆盖,
# 可显式扩展 max_month:max_month = pd.Timestamp("2023-12-31")
full_months = pd.date_range(min_month, max_month, freq="M")
# 步骤 2:构造宽表 —— 以 submissionmonth 为行索引,forecastmonth 为列,cost 为值
# 先设置复合索引,再 unstack 将 forecastmonth 提升为列
wide_df = (input_data
.set_index(["submissionmonth", "forecastmonth"])["cost"]
.unstack("forecastmonth"))
# 步骤 3:按完整月份序列 reindex(自动引入 NaN 行),并前向填充整行
filled_wide = (wide_df
.reindex(full_months.strftime("%b-%Y"), axis=0)
.ffill())
# 步骤 4:stack 回长格式,并重置索引
output_data = (filled_wide
.stack("forecastmonth")
.reset_index(name="cost"))
# 步骤 5:还原原始列顺序(可选但推荐)
output_data = output_data[input_data.columns]
print(f"Input shape: {input_data.shape} → Output shape: {output_data.shape}")
output_data.head(10)⚠️ 重要注意事项:
- 分组逻辑隐含在结构中:本方法天然按 submissionmonth 分组填充,无需显式 groupby,因 reindex + ffill() 是沿新索引(时间轴)逐行操作,每行即代表一个提交快照。
- forecastmonth 必须完全一致:源数据中同一 submissionmonth 下的 forecastmonth 集合需统一(如 Jan-2023 行必须含 Jan–Apr),否则 unstack 会产生缺失列,影响填充完整性。建议预处理校验各组 forecastmonth 的覆盖范围。
- 当前月扩展:示例中 max_month 来自数据最大 submissionmonth(Oct-2023),但业务要求覆盖至 Dec-2023。此时应手动设定 max_month = pd.Timestamp("2023-12-31"),确保 full_months 包含 Dec-2023。
- 性能提示:对于百万级数据,避免多次 reset_index/set_index;可考虑 pd.MultiIndex.from_product 构造全量索引后 reindex,进一步优化。
该方案兼顾准确性与可维护性,是处理“多版本时间快照+跨期继承”类问题的标准 Pandas 模式。

















