python - 为什么 pandas 在日期索引表中查找日期时会生成 KeyError?

标签 python pandas numpy date datetime

考虑以下代码:

date_index = np.array(['2019-01-01', '2019-01-02'], dtype=np.datetime64)
df = pd.DataFrame({'a': np.array([1, 2])}, index=date_index)
date_to_lookup = date_index[0]
print(df.at[date_to_lookup, 'a'])

人们可能希望它能工作并打印 1。然而(至少在 Anaconda python 3.7.3 和 Pandas 0.24.2 中)它失败并出现以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../site-packages/pandas/core/indexing.py", line 2270, in __getitem__
    return self.obj._get_value(*key, takeable=self._takeable)
  File ".../site-packages/pandas/core/frame.py", line 2771, in _get_value
    return engine.get_value(series._values, index)
  File "pandas/_libs/index.pyx", line 81, in pandas._libs.index.IndexEngine.get_value
  File "pandas/_libs/index.pyx", line 89, in pandas._libs.index.IndexEngine.get_value
  File "pandas/_libs/index.pyx", line 447, in pandas._libs.index.DatetimeEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 987, in pandas._libs.hashtable.Int64HashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 993, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 17897

appears Pandas DataFrame 和 Series 对象总是将日期存储为 dtype 'datetime64[ns]''datetime64[ns, tz]',问题出现是因为 Pandas 自动转换 'datetime64[D]' 在创建索引时 dtype 为 'datetime64[ns]',但在该索引中查找元素时不会这样做。我可以通过将 key 转换为 'datetime64[ns]' 来避免上述错误。例如。以下两行都成功打印了 1:

print(df.at[pd.to_datetime(date_to_lookup), 'a'])
print(df.at[date_to_lookup.astype('datetime64[ns]'), 'a'])

这种行为(在创建索引时自动转换数据类型,但在查找元素时不转换)对我来说似乎违反直觉。以这种方式实现的原因是什么?是否有一些编码风格应该遵循以避免这样的错误?还是我应该提交错误?

最佳答案

您可以通过使用 DataFrame.iat 按位置选择来避免这种情况和 Index.get_loc a 列的位置:

print(df.iat[0, df.columns.get_loc('a')])
#alternative
#print(df.iloc[0, df.columns.get_loc('a')])
1

另一个想法是使用 df.index 来选择 date_index[0]:

print(df.at[df.index[0], 'a'])

关于python - 为什么 pandas 在日期索引表中查找日期时会生成 KeyError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58796498/

相关文章:

python - 在给定索引列表的情况下将多行插入数据帧的最快方法(python)

python - 在字符串中搜索符合特定条件的子串

python - 在 2D numpy 数组中有效地找到正值的索引范围

python - 从使用原始 sql 导出到 django 中的 CSV/Excel 文件

python - 动画在 Python 中不起作用

python - 根据输入类型选择行为的最 Pythonic 方式?

python - 在不使用 for 循环的情况下删除 numpy 数组的前导零

python - 在 numpy Capi 中创建动态数组

pandas - 工作日和一天中不同时间的平均参与度热图

python - 从随机生成的数字中抽样?