无法通过pandas中的日期索引调用行

问题描述 投票:0回答:1

我正在尝试加载 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'
python pandas dataset
1个回答
0
投票
  • error
    消息表明您正在尝试访问名为“2017-01”的列而不是行。要基于日期索引访问行,您可以使用
    .loc
    访问器。
appl_df = pd.read_csv('../excelPandas/aapl_tsa1.csv')
appl_df['Date'] = pd.to_datetime(appl_df.Date, format='mixed')

# Set the 'Date' column as the index
appl_df = appl_df.set_index('Date')
appl_df = appl_df.drop('Date', axis='columns')
# Access the 'Close' values for all rows in January 2017
print(appl_df.loc['2017-01', 'Close'])
© www.soinside.com 2019 - 2024. All rights reserved.