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

如何基于Pandas已有列创建时间序列的1月/2月预测列?

解决Pandas创建月份预测列的问题

首先,你的循环代码逻辑完全偏离需求——你是在把Month列值与列名匹配的单元格设为None,自然只会得到空值。要实现1-M/2-M预测列,核心是根据每行的Month值,提取下一个月和下下个月对应列的数值。

具体实现步骤(以你的月份序列June/July/Aug为例)

假设你的原始DataFrame结构如下:

import pandas as pd

data = {
    'Month': ['June', 'July', 'Aug'],
    'June': [100, 150, 200],
    'July': [120, 160, 220],
    'Aug': [130, 170, 230]
}
df = pd.DataFrame(data)

方法1:用apply实现(直观易读)

先定义月份的顺序映射,再逐行提取对应月份的数值:

# 定义月份顺序,后续有新增月份直接在这里添加
month_order = ['June', 'July', 'Aug']
# 建立月份到索引的映射
month_to_idx = {month: idx for idx, month in enumerate(month_order)}

# 创建1-M Forecast(下一个月的数值)
df['1-M Forecast'] = df.apply(
    lambda row: row[month_order[month_to_idx[row['Month']]+1]] 
    if month_to_idx[row['Month']]+1 < len(month_order) 
    else pd.NA,
    axis=1
)

# 创建2-M Forecast(下下个月的数值)
df['2-M Forecast'] = df.apply(
    lambda row: row[month_order[month_to_idx[row['Month']]+2]] 
    if month_to_idx[row['Month']]+2 < len(month_order) 
    else pd.NA,
    axis=1
)

方法2:矢量化实现(大数据集更高效)

避免逐行循环,用Pandas的矢量化操作提升性能:

month_order = ['June', 'July', 'Aug']
month_to_idx = {month: idx for idx, month in enumerate(month_order)}

# 先把Month列转成对应的索引位置
df['month_pos'] = df['Month'].map(month_to_idx)

# 提取1-M预测值
df['1-M Forecast'] = df.lookup(
    df.index, 
    df['month_pos'].add(1).map(lambda x: month_order[x] if x < len(month_order) else None)
)
# 超出月份范围的设为缺失值
df['1-M Forecast'] = df['1-M Forecast'].where(df['month_pos']+1 < len(month_order), pd.NA)

# 提取2-M预测值
df['2-M Forecast'] = df.lookup(
    df.index, 
    df['month_pos'].add(2).map(lambda x: month_order[x] if x < len(month_order) else None)
)
df['2-M Forecast'] = df['2-M Forecast'].where(df['month_pos']+2 < len(month_order), pd.NA)

# 删除临时列
df.drop('month_pos', axis=1, inplace=True)

最终结果

运行后你会得到符合预期的DataFrame:

MonthJuneJulyAug1-M Forecast2-M Forecast
June100120130120130
July150160170170
Aug200220230

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 10:25:07