pandas中如何用历史同期平均值为DataFrame追加当月未来日期数据
你之前的分组代码直接赋值给df会覆盖原始数据,建议先把历史均值存在单独变量里,避免原始数据丢失,完整实现流程如下:
1. 基础环境准备与参数确认
首先确保你的原始数据日期列已经转成datetime格式并设为索引,同时确定待补充的日期范围:
import pandas as pd from pandas.tseries.offsets import MonthEnd # 若原数据还未处理日期格式,先执行这两行 df['Date'] = pd.to_datetime(df['Date']) df = df.set_index('Date').sort_index() # 计算需要补充的日期区间:原数据最大日期后1天 到 当月最后一天 max_exist_date = df.index.max() current_month_end = max_exist_date + MonthEnd(0) need_fill_dates = pd.date_range(start=max_exist_date + pd.Timedelta(days=1), end=current_month_end, freq='D')
2. 计算10年历史同期均值
# 不要覆盖原df,把均值存在单独变量 hist_mean = df.groupby([df.index.month, df.index.day, 'Type'])['Value'].mean().reset_index() # 重命名列方便后续匹配 hist_mean.columns = ['month', 'day', 'Type', 'Value']
3. 生成待补充的空数据结构
给每个待补日期生成A、B两类的空记录,同时提取月、日作为匹配键:
# 生成待补数据的基础结构:日期和Type的笛卡尔积 fill_df = pd.MultiIndex.from_product([need_fill_dates, ['A', 'B']], names=['Date', 'Type']).to_frame(index=False) # 提取月、日用于匹配历史均值 fill_df['month'] = fill_df['Date'].dt.month fill_df['day'] = fill_df['Date'].dt.day
4. 匹配均值并拼接回原数据
# 关联历史均值拿到Value fill_df = fill_df.merge(hist_mean, on=['month', 'day', 'Type'], how='left') # 删掉辅助用的month、day列,只保留需要的三列 fill_df = fill_df[['Date', 'Type', 'Value']] # 把fill_df的Date设为索引和原数据对齐,再拼接 fill_df = fill_df.set_index('Date') # 合并原数据和补充数据 final_df = pd.concat([df, fill_df], axis=0).sort_index()
特殊情况说明
如果待补日期包含2月29日,且过去10年没有对应的历史数据,Value会出现空值,你可以根据业务需求用fillna()补充默认值即可。
内容的提问来源于stack exchange,提问作者vvv
相关产品推荐
相关产品推荐

