Compustretch
Compustretch

Reputation: 127

Key error "Date not in index" only when adding Date to 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

Upvotes: 1

Views: 10112

Answers (3)

BENY
BENY

Reputation: 323366

When you do plot

df['Date'] = pd.to_datetime(df.Date, infer_datetime_format=True) 
df.set_index('Date', inplace=True)
df['Close'].plot()# set the index as x-axis for itself

enter image description here

Upvotes: 0

Sumanth Rao
Sumanth Rao

Reputation: 378

I am assuming you want a line plot of the years on the x axis and close on y axis.

Changing the last line to :

df.plot('Date')

should do the trick.

To make the plot look more appealing you can replace the line:

   df['Date'] = pd.to_datetime(df.Date, infer_datetime_format=True) 

with:

   df['Date'] =  pd.to_datetime(df['Date'], format='%Y-%M-%d')

Upvotes: 0

Allen Qin
Allen Qin

Reputation: 19957

Can you try:

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

instead of:

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

Upvotes: 3

Related Questions