python - 仅在将日期添加到索引时出现关键错误“日期不在索引中”
问题描述
考虑到代码的简单程度,这令人困惑,但在不同的 Linux 和 OSX 机器上却给出了相同的错误。如果 df.set_index('Date', inplace=True) 运行,则 plot(x='Date') 返回 KeyError: "['Date'] not in index" -- 但是如果 df.set_index() 被注释掉,错误消失。
import pandas as pd
import matplotlib.pyplot as plot
df = pd.read_csv('historical_price_data.csv')
# Seemingly makes no difference either way.
df.columns = ['Date', 'Close']
df['Date'] = pd.to_datetime(df.Date, infer_datetime_format=True)
# Uncommenting this line results in error (below) when plot(x='Date') is called.
df.set_index('Date', inplace=True)
# Seemingly makes no difference.
# df.sort_index(inplace=True)
# If set_index('Date') above, then plot(x='Date') returns KeyError: "['Date'] not in index"
df[['Date', 'Close']].plot(x='Date')
plot.show()
这是我正在使用的数据集:
Date,Close
2018-08-29,7059.7
2018-08-28,7071.01
2018-08-27,6911.9
2018-08-26,6709.98
2018-08-25,6737.52
2018-08-24,6690.88
2018-08-23,6526.36
2018-08-22,6359.99
2018-08-21,6475.9
2018-08-20,6258.74
解决方案
你能试一下吗:
df.set_index('Date', inplace=True, drop=False)
代替:
df.set_index('Date', inplace=True)
推荐阅读
- flask - 使用 .sh 启动 gunicorn 时出现问题(没有名为“.0”的模块)
- sql - 显示截至当前月份的所有月份的计数,包括零计数
- java - 如何模拟地图类并模拟返回map.size
- javascript - 如果一个包在 npm 依赖项中但从不使用,它会被 webpack 打包吗
- java - 将客户电子邮件列表上传到 Google Ads Management API
- python - 在 BeautifulSoup 的 div 中从视频标签中查找 src
- python - 在 Django 中从数据库中存储和运行用户定义的函数
- google-apps-script - 如何将重复出现的 csv 从 gmail 导出到我的 gdrive
- android - Android MVVM:直接在片段中使用 Glide 会破坏 MVVM 模式吗?
- elasticsearch - Google Cloud 上的 Elasticsearch 和 Apache 之间的响应时间滞后