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

Pandas日期转换报错:[month]缺失,但已传入月份值

解决ValueError: to assemble mappings requires at least that [year, month, day] be specified错误

错误原因

你调用pd.to_datetime()时传入的DataFrame列名不符合pandas的识别规则:pandas默认会寻找**小写的year、month、day**列,而你的代码里用的是Year(大写Y)、MonthNum(非month)、DAY(大写D),导致pandas无法识别月份字段,从而抛出该错误。

解决方案

提供两种可行的修复方式:

方式一:重命名列名匹配pandas预期

将列名改为pandas默认识别的year、month、day,再调用to_datetime:

# 重命名列并添加固定的day字段
date_df = df[['Year', 'MonthNum']].rename(columns={'Year': 'year', 'MonthNum': 'month'}).assign(day=1)
df['Date'] = pd.to_datetime(date_df)

方式二:直接拼接日期字符串(更直观)

不需要依赖列名规则,直接用年份和月份数字拼接成YYYY-MM格式的字符串,pandas会自动补全日期为当月第一天:

df['Date'] = pd.to_datetime(df['Year'].astype(str) + '-' + df['MonthNum'].astype(str))

修复后的完整代码(以方式一为例)

import pandas as pd

# 示例数据
data = {
    'Year': [2021, 2021, 2021, 2022, 2022, 2023, 2023],
    'Month': ['january', 'february', 'march', 'january', 'february', 'march', 'april'],
    'OrderCount': [60, 55, 70, 64, 56, 76, 70]
}
df = pd.DataFrame(data)

# 月份名称转数字
month_map = {
    'january': 1, 'february': 2, 'march': 3, 'april': 4, 'may': 5, 'june': 6,
    'july': 7, 'august': 8, 'september': 9, 'october': 10, 'november': 11, 'december': 12
}

df['Month'] = df['Month'].str.lower()
df['MonthNum'] = df['Month'].map(month_map)

# 转换数据类型
df['Year'] = df['Year'].astype(int)
df['MonthNum'] = df['MonthNum'].astype(int)

# 修复后的日期转换
date_df = df[['Year', 'MonthNum']].rename(columns={'Year': 'year', 'MonthNum': 'month'}).assign(day=1)
df['Date'] = pd.to_datetime(date_df)

print(df)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 04:41:11