在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
相关产品推荐
相关产品推荐

