我试图加载所有的股票价格从2017年1月,我这样做是通过使用datetimeindex
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)
这是调用appl_df ['2017 - 01']后弹出的数据集和错误
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]
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'
1条答案
按热度按时间rseugnpd1#
error
消息表明您正在尝试访问名为“2017-01”的列而不是行。若要基于日期索引访问行,可以使用.loc
访问器。