首页 > 解决方案 > 仅在将日期添加到索引时出现关键错误“日期不在索引中”

问题描述

考虑到代码的简单程度,这令人困惑,但在不同的 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

标签: pythonpython-2.7pandasmatplotlib

解决方案


你能试一下吗:

df.set_index('Date', inplace=True, drop=False)

代替:

df.set_index('Date', inplace=True)

推荐阅读