python-3.x - 奇怪的 Pandas 日期切片行为(不切片日期)

标签 python-3.x pandas datetime

我可能会在这里遗漏一些东西,但我相信 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/

相关文章:

Python 将 DOWN 时间舍入为 5 分钟

python - 如何在 Python 中使用 for 循环用 NA 替换缺失值

list - 需要澄清 python 中列表的扩展函数。请检查下面的代码

python - 如果 Dataframe 中的数据属于同一流,如何对它们进行分组?

python - Pandas stack/groupby 制作一个新的数据框

python - 结合 Pandas 数据框

java - 将未知日期格式的字符串表示形式转换为 Java 中的日期

delphi - 在 SQLite 数据库(Delphi)中存储日期时间值的最佳方式

python - 使用标识符之间的关系创建数组

python - 在 apply 中向量化一个非常简单的 pandas lambda 函数