pandas DataFrame 从 DateTimeIndex 中选择行列表 - KeyError。理解为什么

pandas DataFrame selecting list of rows from DateTimeIndex - KeyError. Understanding why

我想了解为什么会出现此错误。我已经有了针对这个问题的解决方案,它实际上已经解决了 ,只需要了解为什么它没有像我预期的那样工作。

我想了解为什么会抛出 KeyError:

dates = pd.date_range('20130101', periods=4)
df = pd.DataFrame(np.identity(4), index=dates, columns=list('ABCD'))
df.loc[['20130102', '20130103'],:]

反馈如下:

KeyError: "None of [['20130102', '20130103']] are in the [index]"

所述,解决方法就是:

df.loc[pd.to_datetime(['20130102','20130104']),:]

所以问题肯定出在 loc 将字符串列表作为从 DateTimeIndex 中进行选择的参数的方式。但是,我可以看到以下调用适用于此功能:

df.loc['20130102':'20130104',:]

df.loc['20130102']

我想了解它是如何工作的,并感谢我可以使用任何资源来预测此函数的行为,具体取决于它的调用方式。我从 pandas 文档中阅读了 Indexing and Selecting Data and Time Series/Date functionality,但找不到对此的解释。

通常,当您将类似对象的数组传递给 loc 时,Pandas 将尝试在索引中找到该数组的每个元素。如果找不到,您将得到 KeyError。和!当索引中的值为 Timestamps 时,您传递了一个字符串数组...因此这些字符串肯定不在索引中。

但是,Pandas 也试图让事情变得更容易。特别是,对于 DatetimeIndex,如果您要传递一个字符串标量

df.loc['20130102']

A    0.0
B    1.0
C    0.0
D    0.0
Name: 2013-01-02 00:00:00, dtype: float64

Pandas 将尝试将该标量解析为 Timestamp 并查看该值是否在索引中。

如果您要传递 slice 对象

df.loc['20130102':'20130104']

              A    B    C    D
2013-01-02  0.0  1.0  0.0  0.0
2013-01-03  0.0  0.0  1.0  0.0
2013-01-04  0.0  0.0  0.0  1.0

Pandas 还将尝试将切片对象的位解析为 Timestamp 和 return 适当切片的数据帧。

您的 KeyError 只是超过了 Pandas 开发人员有时间编写代码的帮助极限。