【发布时间】:2019-04-10 21:58:01
【问题描述】:
我有一个 Pandas 数据框,其中包含一些日期和价格。 我的索引包含日期(由 df.set_index 归属)和不同资产的列。
看起来像这样,但是是 [6069 行 x 306 列]
OVER_price DI1J95_price
1995-01-02 48.61 45.662
1995-01-03 50.12 45.542
2019-03-11 6.40 NaN
我有一个类作为参数 calcDate 是索引日期,diCode 是列中的资产名称,diPanel 是我的数据框。
如果我在班级 df.loc 中运行:
#Find Prices
self.diPrice = diPanel.loc[self.calcDate, self.diCode]
我得到了预期的价格,没问题。
如果我将代码更改为 df.at:
#Find Prices
self.diPrice = diPanel.at[self.calcDate, self.diCode]
我得到一个 KeyError 异常。例如 2019-03-11 作为 calcDate 返回:
发生异常:KeyError 17966
关于发生了什么的任何线索? 谢谢
基于 Rich Andrews 的回答:
似乎正在发生的事情是
.at对索引的类型有疑问。
实际上问题在于日期时间类型。 Allmy 代码基于numpy.datetime64[D] 类型。但是我的 DataFrame 的索引是 pandas.Timestamp。
我能够仔细检查是否正在运行:
# Print last Index value and Type
print(type(diPanel.index[6068]))
print(diPanel.index[6068])
返回:
2019-03-11 00:00:00
<class 'pandas._libs.tslibs.timestamps.Timestamp'>
对于我的搜索参数:
# Print last Index value and Type
print(type(self.calcDate))
print(self.calcDate)
返回:
<class 'numpy.datetime64'>
2019-03-11
由于某种原因,.loc 能够绕过类型不匹配而.at 不能。
有没有人遇到过同样的问题并且知道为什么这两种方法的行为不同?
谢谢
【问题讨论】: