仅当将日期添加到索引中

时间:2018-09-06 01:30:16

标签: python python-2.7 pandas matplotlib

鉴于代码的简单程度,这令人困惑,但是在单独的Linux和OSX机器上却给出了相同的错误。如果运行df.set_index('Date',inplace = True),则plot(x ='Date')返回KeyError:“ ['Date']不在索引中” –但是,如果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

3 个答案:

答案 0 :(得分:1)

您可以尝试:

dbconnect.php

代替:

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

答案 1 :(得分:0)

我假设您想要在x轴上绘制年份并在y轴上绘制年份的线图。

将最后一行更改为:

df.plot('Date')

应该可以解决问题。

要使绘图看起来更具吸引力,您可以替换以下行:

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

具有:

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

答案 2 :(得分:0)

当您绘图时

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