python - Pandas loc 给了我 keyerror,索引是日期
问题描述
我有这个包含 EOD 股票价格的数据集
YAR.OL NHY.OL ... DNB.OL SBO.OL
date ...
1986-03-13 NaN NaN ... NaN NaN
1986-03-14 NaN NaN ... NaN NaN
1986-03-17 NaN NaN ... NaN NaN
1986-03-18 NaN NaN ... NaN NaN
1986-03-19 NaN NaN ... NaN NaN
... ... ... ... ... ...
2020-07-24 377.799988 26.740000 ... 144.500000 51.000000
2020-07-27 381.799988 26.350000 ... 142.199997 50.599998
2020-07-28 382.399994 26.490000 ... 142.000000 50.200001
2020-07-29 377.899994 26.389999 ... 142.100006 50.799999
2020-07-30 372.000000 25.049999 ... 137.149994 49.799999
索引是日期。但是,当我尝试做
df.loc[['2020-07-29']]
我收到一条错误消息:KeyError: '2010-07-29'
或者当我这样做时:
df.loc[['2010-06-29']]
我得到KeyError:“[Index(['2010-06-29'], dtype='object', name='date')] 中没有一个在 [index] 中”
我在打印 df.index 时检查了索引,并且该值确实存在。
Index([1986-03-13, 1986-03-14, 1986-03-17, 1986-03-18, 1986-03-19, 1986-03-20,
1986-03-21, 1986-03-24, 1986-03-25, 1986-03-26,
...
2020-07-17, 2020-07-20, 2020-07-21, 2020-07-22, 2020-07-23, 2020-07-24,
2020-07-27, 2020-07-28, 2020-07-29, 2020-07-30],
dtype='object', name='date', length=8667)
有谁知道为什么会这样?
解决方案
让我们将索引的 dtype 更改为 datetime 以为您的数据框创建 DateTimeIndex。
df.index = pd.to_datetime(df.index)
现在,让我们使用df.loc['2010-07-29']
.
推荐阅读
- ruby - Ruby:在标签和标签属性之间提取文本?
- python - 并排绘制两个图(seaborn 和子图)
- sql - 在 Sequelize 模型中使用 Postgres 生成的列
- spring-boot - Thymeleaf 看不到 For-each 变量
- node.js - 如何在 Github 操作中设置 Dockerfile ARG
- ruby-on-rails - Ruby on Rails 6 中的主动存储
- javascript - TypeError:未定义不是对象(评估“connection.connect”)
- discord - Canvacord .setBackground 错误:服务器以 526 响应
- sql - BigQuery - 从 UTC 转换为 CET 时,DateTime 会产生意外的时差
- reactjs - 在 useLocation 上设置类型