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

如何基于5年平均数据预测未来值并将预测结果与历史数据集合并绘图

解决方法
  • 第一步:处理预测结果的索引格式
    你当前通过groupby得到的df_fut是(月、日)二级索引结构,无法直接和带完整年份的历史数据合并,首先需要将其匹配到未来12个月的完整日期序列上:
import pandas as pd

# 构造你需要预测的时间段的日期序列,此处以预测2016年全年为例
future_dates = pd.date_range(start="2016-01-01", end="2016-12-31", freq="D")
# 给预测序列加月、日匹配键
df_future = pd.DataFrame(index=future_dates)
df_future["month"] = df_future.index.month
df_future["day"] = df_future.index.day

# 重置预测结果的索引,用于匹配
df_fut = df_fut.reset_index()
# 匹配对应月日的历史平均值
df_future = df_future.merge(df_fut, on=["month", "day"], how="left").set_index(future_dates)[["Volume"]]

# 可选:如果预测年份是闰年,2月29日无历史平均值时,用线性插值补全
df_future["Volume"] = df_future["Volume"].interpolate()
  • 第二步:合并历史数据与预测数据
    给两个数据集加标识列区分数据类型,再纵向拼接:
# 给历史数据加标识
df["data_type"] = "历史数据"
# 给预测数据加标识
df_future["data_type"] = "预测数据"
# 拼接合并
df_all = pd.concat([df, df_future], axis=0)
  • 第三步:统一绘图
    直接按数据类型区分样式绘图即可:
import matplotlib.pyplot as plt

plt.rcParams["font.sans-serif"] = ["SimHei"] # 解决中文显示问题
plt.figure(figsize=(16, 6))
# 绘制历史数据
df_all[df_all["data_type"] == "历史数据"]["Volume"].plot(label="历史销量", color="#1f77b4")
# 绘制预测数据
df_all[df_all["data_type"] == "预测数据"]["Volume"].plot(label="预测销量", color="#ff7f0e", linestyle="--")

plt.legend()
plt.xlabel("日期")
plt.ylabel("销量(Volume)")
plt.title("5年历史销量与未来12个月季节平均预测值")
plt.grid(alpha=0.3)
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:15:08