【发布时间】:2021-04-21 02:32:56
【问题描述】:
我有一个名为 'holidays' 的 DataFrame,Date 是索引,如下所示,为什么 Out[7] 和 Out[8] 会发生? 如何像 Out[9] 一样对索引名称为 2020-01-01 的行进行切片,非常感谢
holidays:
Out[1]:
CNY USD HKD JPY EUR AUD CAD
Date
2020-01-01 1 1 1 1 1 1 1
2020-01-02 0 0 0 1 0 0 0
2020-01-03 0 0 0 1 0 0 0
2020-01-06 0 0 0 0 0 0 0
2020-01-07 0 0 0 0 0 0 0
holidays.index:
Out[2]:
Index([2020-01-01, 2020-01-02, 2020-01-03, 2020-01-06, 2020-01-07], dtype='object', name='Date', length=130)
holidays.index[0]:
Out[3]:datetime.date(2020, 1, 1)
holidays.index[0] == '2020-01-01'
Out[4]: False
xx = holidays.index[0]
xx
Out[5]: datetime.date(2020, 1, 1)
holidays.index[0] == xx
Out[6]: True
holidays.index[0] == datetime.date(2020, 1, 1)
Out[7]:
Traceback (most recent call last):
File "<ipython-input-25-f72e3a7fa605>", line 1, in <module> holidays.index[0] == datetime.date(2020, 1, 1)
TypeError: descriptor 'date' for 'datetime.datetime' objects doesn't apply to a 'int' object
cfets_holidays['2020-01-01']
Out[8]:
Traceback (most recent call last):
File "C:\Users\****\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 3080, in get_loc
return self._engine.get_loc(casted_key)
File "pandas\_libs\index.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 4554, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 4562, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: '2020-01-01'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<ipython-input-33-a412e24bcffd>", line 1, in <module>
holidays['2020-01-01']
File "C:\Users\****\Anaconda3\lib\site-packages\pandas\core\frame.py", line 3024, in __getitem__
indexer = self.columns.get_loc(key)
File "C:\Users\****\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 3082, in get_loc
raise KeyError(key) from err
KeyError: '2020-01-01'
cfets_holidays.iloc[0:1]
Out[9]:
CNY USD HKD JPY EUR AUD CAD
Date
2020-01-01 1 1 1 1 1 1 1
【问题讨论】:
标签: python pandas dataframe datetime