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

使用pd.to_datetime合并时间列报错,已排查空值仍提示缺少month

问题分析:合并日期时间列触发ValueError错误

问题背景

编写Python代码批量处理Excel文件,目标是将Year、Mon、Day、Hour四列合并为单个time时间列,但运行时抛出错误:

ValueError: to assemble mappings requires at least that [year, month, day] be specified: [month] is missing.

已确认DataFrame中不存在空值。

代码示例

import pandas as pd
import os


def process_xls(file_path):
    df = pd.read_excel(file_path)
    (filepath, filename) = os.path.split(file_path)
    # 插入新列
    df = df.drop(df.columns[0], axis=1)
    df.insert(0, 'name', os.path.splitext(filename)[0])

    null_positions = df.isnull()
    df.insert(2, 'time', pd.to_datetime(df[['Year', 'Mon', 'Day', 'Hour']]))
    # 删除原来的四列数据
    df = df.drop(columns=['Year', 'Mon', 'Day', 'Hour'])
    return df


def process_folder(folder_path):
    for file_name in os.listdir(folder_path):
        if file_name.endswith('.xls'):
            file_path = os.path.join(folder_path, file_name)
            df = process_xls(file_path)
            new_file_name = 'new_' + file_name
            new_file_path = os.path.join(folder_path, new_file_name)
            df.to_excel(new_file_path, index=False)


folder_path = r'H:\agriculture\QIXIANG\DATA_station'
process_folder(folder_path)

错误原因

pd.to_datetime()通过列名识别日期组件时,要求列名匹配标准字段名(如year/month/day/hour,不区分大小写)。你的列名用了Mon而非标准的month,导致pandas无法识别该列为月份数据,进而判定缺少月份信息触发错误。

解决方案

方案1:指定格式字符串(推荐)

直接拼接日期时间字符串并指定格式,无需修改列名:

# 替换原合并时间列的代码
df.insert(2, 'time', pd.to_datetime(
    df['Year'].astype(str) + '-' + df['Mon'].astype(str) + '-' + df['Day'].astype(str) + ' ' + df['Hour'].astype(str) + ':00:00',
    format='%Y-%m-%d %H:%M:%S'
))

方案2:重命名列名匹配标准字段

先将列名改为pandas可识别的标准名称,再执行合并:

# 重命名列
df.rename(columns={'Mon': 'month', 'Year': 'year', 'Day': 'day', 'Hour': 'hour'}, inplace=True)
# 合并时间列
df.insert(2, 'time', pd.to_datetime(df[['year', 'month', 'day', 'hour']]))
# 可选:合并后改回原列名(若需保留原列名)
df.rename(columns={'month': 'Mon', 'year': 'Year', 'day': 'Day', 'hour': 'Hour'}, inplace=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 00:57:29