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

在Pandas中将[月1-月3 年份]格式日期转为中间月份的问题

解决日期格式转换问题:将「起始月份-结束月份 年份」转为中间月份

你的代码核心问题在于:month_dict是月份缩写到数字字符串的映射,但最后返回时你试图用数字字符串(比如'4')去查询这个字典,而字典的键是月份缩写(比如'Apr'),这会直接抛出KeyError。

修正后的代码方案

我们需要构建双向月份映射,同时确保计算逻辑正确:

def convert_date_format(date_str):
    # 拆分起始月份、结束月份和年份
    start_month, end_month_year = date_str.split('-')
    end_month, year_str = end_month_year.split()
    
    # 月份缩写<->数字的双向映射
    month_abbr_to_num = {'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 
                         'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08', 
                         'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12'}
    month_num_to_abbr = {v: k for k, v in month_abbr_to_num.items()}
    
    # 转换为数字并计算中间月份
    start_month_num = int(month_abbr_to_num[start_month])
    end_month_num = int(month_abbr_to_num[end_month])
    middle_month_num = (start_month_num + end_month_num) // 2
    
    # 格式化为两位数的数字字符串,再映射回缩写
    middle_month_str = f"{middle_month_num:02d}"
    # 返回「Apr 1992」格式,若要「04-1992」格式,替换为:return f"{middle_month_str}-{year_str}"
    return f"{month_num_to_abbr[middle_month_str]} {year_str}"

# 应用到DataFrame列
unemp_p_df['Months'] = unemp_p_df['Months'].apply(convert_date_format)
unemp_p_df.head()

关键修正点

  • 新增month_num_to_abbr字典,通过反转原字典实现从数字字符串到月份缩写的映射
  • 使用f"{middle_month_num:02d}"确保中间月份数字始终是两位数(比如4转为'04'),匹配字典的键格式
  • 保留两种输出格式的切换选项,可按需调整

大数据集优化建议

如果数据量较大,推荐用Pandas矢量化操作替代apply,提升处理效率:

import pandas as pd

# 定义映射字典
month_abbr_to_num = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
                     'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
month_num_to_abbr = {v: k for k, v in month_abbr_to_num.items()}

# 拆分列
unemp_p_df[['start_month', 'end_month_year']] = unemp_p_df['Months'].str.split('-', expand=True)
unemp_p_df[['end_month', 'year']] = unemp_p_df['end_month_year'].str.split(expand=True)

# 转换月份为数字并计算中间值
unemp_p_df['start_num'] = unemp_p_df['start_month'].map(month_abbr_to_num)
unemp_p_df['end_num'] = unemp_p_df['end_month'].map(month_abbr_to_num)
unemp_p_df['middle_num'] = (unemp_p_df['start_num'] + unemp_p_df['end_num']) // 2

# 生成目标格式
unemp_p_df['Months'] = unemp_p_df['middle_num'].map(month_num_to_abbr) + ' ' + unemp_p_df['year']
# 若要数字格式:unemp_p_df['Months'] = unemp_p_df['middle_num'].apply(lambda x: f"{x:02d}") + '-' + unemp_p_df['year']

# 清理临时列
unemp_p_df = unemp_p_df.drop(['start_month', 'end_month_year', 'end_month', 'year', 'start_num', 'end_num', 'middle_num'], axis=1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:33:11