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

pxy2qtax  于 2023-09-29  发布在  其他
关注(0)|答案(1)|浏览(100)

我试图加载所有的股票价格从2017年1月,我这样做是通过使用datetimeindex

  1. appl_df = pd.read_csv('../excelPandas/aapl_tsa1.csv')
  2. appl_df['Date'] = pd.to_datetime(appl_df.Date, format='mixed')
  3. appl_df = appl_df.set_index(appl_df.Date)
  4. appl_df = appl_df.drop('Date', axis='columns')
  5. print(appl_df)
  6. # Loading all the data samples from appl_df['2017-01']
  7. print(appl_df['2017-01'].Close)

这是调用appl_df ['2017 - 01']后弹出的数据集和错误

  1. Open High Low Close Volume
  2. Date
  3. 2017-07-07 142.90 144.75 142.90 144.18 19201712
  4. 2017-07-06 143.02 143.50 142.41 142.73 24128782
  5. 2017-07-05 143.69 144.79 142.72 144.09 21569557
  6. 2017-07-03 144.88 145.30 143.10 143.50 14277848
  7. 2017-06-30 144.45 144.96 143.78 144.02 23024107
  8. ... ... ... ... ... ...
  9. 2016-07-15 98.92 99.30 98.50 98.78 30136990
  10. 2016-07-14 97.39 98.99 97.32 98.79 38918997
  11. 2016-07-13 97.41 97.67 96.84 96.87 25892171
  12. 2016-07-12 97.17 97.70 97.12 97.42 24167463
  13. 2016-07-11 96.75 97.65 96.73 96.98 23794945
  14. [251 rows x 5 columns]
  15. Traceback (most recent call last):
  16. File "/Users/my_name/anaconda3/lib/python3.11/site-packages/pandas/core/indexes/base.py", line 3790, in get_loc
  17. return self._engine.get_loc(casted_key)
  18. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  19. File "index.pyx", line 152, in pandas._libs.index.IndexEngine.get_loc
  20. File "index.pyx", line 181, in pandas._libs.index.IndexEngine.get_loc
  21. File "pandas/_libs/hashtable_class_helper.pxi", line 7080, in pandas._libs.hashtable.PyObjectHashTable.get_item
  22. File "pandas/_libs/hashtable_class_helper.pxi", line 7088, in pandas._libs.hashtable.PyObjectHashTable.get_item
  23. KeyError: '2017-01'
  24. The above exception was the direct cause of the following exception:
  25. Traceback (most recent call last):
  26. File "/Users/my_name/PycharmProjects/pandas/ pandasTimeSeriesAnalysis/datetimeIndexAndResample_tsa1.py", line 12, in <module>
  27. print(appl_df['2017-01'].Close)
  28. ~~~~~~~^^^^^^^^^^^
  29. File "/Users/my_name/anaconda3/lib/python3.11/site-packages/pandas/core/frame.py", line 3896, in __getitem__
  30. indexer = self.columns.get_loc(key)
  31. ^^^^^^^^^^^^^^^^^^^^^^^^^
  32. File "/Users/my_name/anaconda3/lib/python3.11/site-packages/pandas/core/indexes/base.py", line 3797, in get_loc
  33. raise KeyError(key) from err
  34. KeyError: '2017-01'
rseugnpd

rseugnpd1#

  • error消息表明您正在尝试访问名为“2017-01”的列而不是行。若要基于日期索引访问行,可以使用.loc访问器。
  1. appl_df = pd.read_csv('../excelPandas/aapl_tsa1.csv')
  2. appl_df['Date'] = pd.to_datetime(appl_df.Date, format='mixed')
  3. # Set the 'Date' column as the index
  4. appl_df = appl_df.set_index('Date')
  5. appl_df = appl_df.drop('Date', axis='columns')
  6. # Access the 'Close' values for all rows in January 2017
  7. print(appl_df.loc['2017-01', 'Close'])

相关问题