【发布时间】:2017-11-16 08:14:50
【问题描述】:
我试图了解为什么会出现此错误。我已经有了这个问题的解决方案,实际上已经解决了here,只需要了解为什么它不能按我的预期工作。
我想了解为什么这会引发 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]"
正如here 解释的那样,解决方案就是这样做:
df.loc[pd.to_datetime(['20130102','20130104']),:]
所以问题肯定出在 loc 将字符串列表作为参数从 DateTimeIndex 中进行选择的方式上。但是,我可以看到此函数可以进行以下调用:
df.loc['20130102':'20130104',:]
和
df.loc['20130102']
我想了解它的工作原理,并感谢我可以使用任何资源来预测此函数的行为,具体取决于它的调用方式。我从 pandas 文档中阅读了 Indexing and Selecting Data 和 Time Series/Date functionality,但找不到对此的解释。
【问题讨论】:
-
如果有人有类似的问题,为我解决的方法是删除重复的索引:` df = df.loc[~df.index.duplicated(keep='first')]; sliced_df = df[start_time:end_time] `
-
以及对索引进行排序:df = df.sort_index()
标签: python pandas dataframe python-datetime keyerror