关键错误“日期不在索引中".仅在将日期添加到索引时 [英] Key error "Date not in index" only when adding Date to index

查看:291
本文介绍了关键错误“日期不在索引中".仅在将日期添加到索引时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于代码的简单程度,这令人困惑,但是在单独的Linux和OSX机器上却给出了相同的错误.如果运行df.set_index('Date',inplace = True),则plot(x ='Date')返回KeyError:"['Date']不在索引中" –但是,如果df.set_index()被注释掉,错误就消失了.

This one is baffling given how simple the code is, and yet it's giving the same error on separate Linux and OSX boxes. If df.set_index('Date', inplace=True) is run, then plot(x='Date') returns KeyError: "['Date'] not in index" -- But if df.set_index() is commented out, the error goes away.

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()

这是我正在使用的数据集:

This is the data set I'm using:

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)

这篇关于关键错误“日期不在索引中".仅在将日期添加到索引时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆