我可能会在这里遗漏一些东西,但我相信 pandas 日期时间切片发生了一些奇怪的事情。这是一个可重现的示例:
import pandas as pd
import pandas_datareader as pdr
testdf = pdr.DataReader('SPY', 'yahoo')
testdf.index = pd.to_datetime(testdf.index)
testdf['2020-11']
在这里我们可以看到,切片查找月份的数据返回了预期的输出。 不过,现在让我们尝试查找与 2020 年 11 月 9 日对应的行。
testdf['2020-11-09']
我们得到以下回溯。
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
C:\Anaconda\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2894 try:
-> 2895 return self._engine.get_loc(casted_key)
2896 except KeyError as err:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: '2020-11-09'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
<ipython-input-78-a42a45b5c3a4> in <module>
----> 1 testdf['2020-11-09']
C:\Anaconda\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
2900 if self.columns.nlevels > 1:
2901 return self._getitem_multilevel(key)
-> 2902 indexer = self.columns.get_loc(key)
2903 if is_integer(indexer):
2904 indexer = [indexer]
C:\Anaconda\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2895 return self._engine.get_loc(casted_key)
2896 except KeyError as err:
-> 2897 raise KeyError(key) from err
2898
2899 if tolerance is not None:
KeyError: '2020-11-09'
在这里我们可以看到键实际上在索引中:
testdf['2020-11'].index
DatetimeIndex(['2020-11-02', '2020-11-03', '2020-11-04', '2020-11-05',
'2020-11-06', '2020-11-09'],
dtype='datetime64[ns]', name='Date', freq=None)
这是一个错误还是我是一个错误?
最佳答案
testdf['2020-11-09']
按列切片,即在列中查找 '2020-11-09'
。您的意思是:
testdf.loc['2020-11-09']
关于python-3.x - 奇怪的 Pandas 日期切片行为(不切片日期),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64770682/