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

Pandas时间序列列重命名触发IndexError: too many indices for array

解决日期列名统一为1月1日及IndexError问题

问题背景

将日期列转置为年份列后,部分列的日期为12月31日,需要统一改为当年1月1日,使用rename方法时触发错误:IndexError: too many indices for array。尝试的代码如下:

df_top100.rename(columns={'2012-12-31 00:00:00': '2012-01-01 00:00:00'}, inplace=True)
#df_top100.rename(columns={'2013-12-31': '2013-01-01'}, inplace=True)
#df_top100.rename(columns={'2016-12-31': '2016-01-01'}, inplace=True)

数据集列名示例:

year    2005-01-01  2006-01-01  2007-01-01  2008-01-01  2009-01-01  2010-01-01  2011-01-01  2012-12-31  2013-12-31  2014-01-01  2015-01-01  2016-12-31
country                                             
Australia   2.0 3.0 3.0 3.0 3.0 3.0 9.0 6.0 8.0 11.0    11.0    6.0

最后一列输出显示列名是带时分秒的datetime格式:

print(df_top100.columns[-1])
# 输出:2016-12-31 00:00:00

错误原因

  1. 列名类型不统一:部分列名是字符串(如2012-12-31),部分是datetime对象(如2016-12-31 00:00:00),导致rename无法正确匹配目标列。
  2. 直接用字符串匹配datetime对象会失败,触发内部数组维度错误(IndexError)。

解决方案

无需逐个列手动重命名,直接统一处理所有列名,将日期改为当年1月1日:

步骤1:统一列名为datetime类型

import pandas as pd

# 将列名转换为datetime格式
df_top100.columns = pd.to_datetime(df_top100.columns)

步骤2:修改所有列的日期为1月1日

# 将每个日期的月份和日期替换为1月1日
df_top100.columns = df_top100.columns.map(lambda dt: dt.replace(month=1, day=1))

步骤3(可选):转换为不带时分秒的字符串格式

如果需要列名显示为YYYY-MM-DD格式:

df_top100.columns = df_top100.columns.strftime('%Y-%m-%d')

验证结果

执行后检查列名:

print(df_top100.columns)

所有列名将统一为YYYY-01-01格式,无错误触发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 02:48:27