gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:36:33 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com