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

在Pandas中基于DatetimeIndex过滤时间序列触发KeyError的原因

Pandas中DatetimeIndex按年份过滤触发KeyError的原因

尝试在Pandas中基于DatetimeIndex过滤时间序列时触发KeyError,运行如下代码会抛出KeyError: '2021':

import pandas as pd

data = {'date':['2021-11-1', '2021-12-1', '2022-01-1', '2022-02-1'],
       'value':['hello', 'bonjour', 'merhaba', 'goeiendag']}

df = pd.DataFrame(data)
df['date'] = pd.to_datetime(df['date'])

df.set_index('date', inplace=True)

print(df['2021'])
#print(df['2021-01'])
#print(df['2021-01-01'])

错误成因

这个错误的核心是Pandas版本兼容性问题:

  • 在Pandas 1.x及更早版本中,支持通过纯年份/月份字符串(如'2021'、'2021-01')直接对DatetimeIndex进行隐式切片查询。
  • 但从Pandas 2.0版本开始,这种写法被彻底移除——此时df['2021']会被Pandas当成列名去查找,而你的DataFrame并没有名为'2021'的列,因此触发KeyError。

解决方法

要实现按年份/月份过滤时间序列,需要使用显式的查询方式:

  • 方法1:使用.loc配合字符串切片(推荐,语法简洁)
# 过滤2021年所有数据
print(df.loc['2021'])
# 过滤2021年1月的所有数据
print(df.loc['2021-01'])
# 过滤指定日期
print(df.loc['2021-11-01'])
  • 方法2:通过索引的时间属性过滤
# 过滤2021年数据
print(df[df.index.year == 2021])
# 过滤2021年11月数据
print(df[(df.index.year == 2021) & (df.index.month == 11)])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 19:22:42