Pandas中使用DatetimeIndex无法筛选2017年1月股票数据的问题
解决DatetimeIndex筛选指定月份数据的KeyError问题
问题代码
appl_df = pd.read_csv('../excelPandas/aapl_tsa1.csv') appl_df['Date'] = pd.to_datetime(appl_df.Date, format='mixed') appl_df = appl_df.set_index(appl_df.Date) appl_df = appl_df.drop('Date', axis='columns') print(appl_df) # Loading all the data samples from appl_df['2017-01'] print(appl_df['2017-01'].Close)
报错信息
数据集输出(包含2016年7月至2017年7月数据):
Open High Low Close Volume Date 2017-07-07 142.90 144.75 142.90 144.18 19201712 2017-07-06 143.02 143.50 142.41 142.73 24128782 2017-07-05 143.69 144.79 142.72 144.09 21569557 2017-07-03 144.88 145.30 143.10 143.50 14277848 2017-06-30 144.45 144.96 143.78 144.02 23024107 ... ... ... ... ... ... 2016-07-15 98.92 99.30 98.50 98.78 30136990 2016-07-14 97.39 98.99 97.32 98.79 38918997 2016-07-13 97.41 97.67 96.84 96.87 25892171 2016-07-12 97.17 97.70 97.12 97.42 24167463 2016-07-11 96.75 97.65 96.73 96.98 23794945 [251 rows x 5 columns]
KeyError报错:
Traceback (most recent call last): File "/Users/my_name/anaconda3/lib/python3.11/site-packages/pandas/core/indexes/base.py", line 3790, in get_loc return self._engine.get_loc(casted_key) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "index.pyx", line 152, in pandas._libs.index.IndexEngine.get_loc File "index.pyx", line 181, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/hashtable_class_helper.pxi", line 7080, in pandas._libs.hashtable.PyObjectHashTable.get_item File "pandas/_libs/hashtable_class_helper.pxi", line 7088, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: '2017-01' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/my_name/PycharmProjects/pandas/ pandasTimeSeriesAnalysis/datetimeIndexAndResample_tsa1.py", line 12, in <module> print(appl_df['2017-01'].Close) ~~~~~~~^^^^^^^^^^^ File "/Users/my_name/anaconda3/lib/python3.11/site-packages/pandas/core/frame.py", line 3896, in __getitem__ indexer = self.columns.get_loc(key) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/my_name/anaconda3/lib/python3.11/site-packages/pandas/core/indexes/base.py", line 3797, in get_loc raise KeyError(key) from err KeyError: '2017-01'
错误原因
新版pandas中,DataFrame['xxx']语法默认用于访问列名,而非行索引切片。你写的appl_df['2017-01']会被解析为查找名为'2017-01'的列,但数据列只有Open、High、Low、Close、Volume,因此触发KeyError。
解决方案
方案1:使用.loc进行行索引切片
这是最规范的方式,明确指定访问行索引:
# 直接筛选2017年1月的Close列 print(appl_df.loc['2017-01', 'Close']) # 或先取整月数据再提取Close列 print(appl_df.loc['2017-01'].Close)
方案2:使用行索引切片语法
也可以直接用切片方式筛选日期范围:
print(appl_df['2017-01':'2017-01'].Close)
方案3:简化数据读取代码
读取CSV时直接将Date列设置为DatetimeIndex,减少代码步骤:
appl_df = pd.read_csv( '../excelPandas/aapl_tsa1.csv', parse_dates=['Date'], index_col='Date' ) # 之后直接用.loc筛选即可 print(appl_df.loc['2017-01'].Close)
额外验证(可选)
若不确定索引类型,可先检查:
print(type(appl_df.index)) # 应输出 <class 'pandas.core.indexes.datetimes.DatetimeIndex'>
内容的提问来源于stack exchange,提问作者Qendala
相关产品推荐
相关产品推荐

