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

如何基于月份列生成正确的Month_Predicted_DT(处理跨年场景下的年份错误问题)

Fixing Year Rollover for Month_Predicted_DT in Your Pandas DataFrame

我完全理解你遇到的跨年日期问题——当处理11月、12月对应的后续月份时,直接套用当前年份生成日期会导致1月、2月的年份错误。不用iterrows或者复杂的np.where也能解决,我们可以利用Pandas的日期偏移特性来处理,更简洁高效。

问题核心分析

你当前的代码把year硬设为当前年份,但实际上后续月份(比如11月之后的12月、1月)的年份需要根据原始基准月份(M)来判断是否跨年:

  • 如果M是November(11月),January对应的年份应该是当前年份+1
  • 如果M是December(12月),January和February的年份都应该是当前年份+1

解决方案步骤

我们可以先把原始的月份名称转换成基准日期,再通过日期偏移来推算每个月份的正确日期,自动处理跨年情况:

  1. 从原始列名M生成基准日期(比如M是November,基准日期就是当前年份-11-01)
  2. 给每个目标月份(M、M+1、M+2)设置对应的偏移量(0、1、2个月)
  3. 用基准日期加上偏移量,直接得到正确的Month_Predicted_DT

完整修正代码

import pandas as pd
from datetime import date

# 读取原始数据
citi = pd.read_excel("Downloads/CITI_2022_05_22(5_22).xlsx")

# 提取目标月份列(M, M+1, M+2)
M = citi.columns[-6]
M_1 = citi.columns[-4]
M_2 = citi.columns[-2]

# 提取相关列
cols = ['agency-term','coupon','year','Cbal',M,M_1,M_2]
citi = citi[cols]

# 第一步:重塑数据(和你原来的stack步骤一致)
citi_new = citi.set_index(cols[0:4]).stack().reset_index()
citi_new.rename(columns={"level_4": "Month", 0 : "CPR", "year" : "vintage"}, inplace = True)

# 第二步:处理日期,解决跨年问题
todays_date = date.today()
current_year = todays_date.year

# 生成M对应的基准日期(比如M是November,就是current_year-11-01)
base_date = pd.to_datetime(f"{current_year}-{pd.to_datetime(M, format='%B').month}-01")

# 创建月份到偏移量的映射:M对应0,M_1对应1,M_2对应2
month_offset_map = {M:0, M_1:1, M_2:2}
citi_new['month_offset'] = citi_new['Month'].map(month_offset_map)

# 计算正确的预测日期:基准日期加上偏移月份
citi_new['Month_Predicted_DT'] = base_date + pd.DateOffset(months=citi_new['month_offset'])

# 可选:提取year和month列(如果需要保留这两列)
citi_new['year'] = citi_new['Month_Predicted_DT'].dt.year
citi_new['month'] = citi_new['Month_Predicted_DT'].dt.month

# 清理临时列
citi_new = citi_new.drop('month_offset', axis=1)

效果验证

比如当M是November(2022年11月)时:

  • November对应的Month_Predicted_DT是2022-11-01
  • December对应的是2022-12-01
  • January对应的是2023-01-01(自动完成跨年)

如果M是December(2022年12月):

  • December对应2022-12-01
  • January对应2023-01-01
  • February对应2023-02-01

这种方法不需要逐个判断月份名称,完全依赖日期偏移逻辑处理,既简洁又能覆盖所有跨年场景,比用iterrows或者np.where更高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 23:22:48