Python Matplotlib DatetimeIndex错误-列中没有任何值

Python Matplotlib DatetimeIndex错误-列中没有任何值,python,pandas,matplotlib,Python,Pandas,Matplotlib,我已经将一些每日日期格式的csv数据重新采样为每月数据,现在希望使用matplotlib可视化。但是,当我尝试绘制重新采样的timeseries数据时,我遇到了以下错误,不确定如何继续。我尝试引用df.index和df.index.values都没有成功 KeyError: "None of [DatetimeIndex(['2019-02-28', '2019-03-31',\n '2019-04-30', '2019-05-31', '2019-06-30', '

我已经将一些每日日期格式的csv数据重新采样为每月数据,现在希望使用matplotlib可视化。但是,当我尝试绘制重新采样的timeseries数据时,我遇到了以下错误,不确定如何继续。我尝试引用
df.index
df.index.values
都没有成功

KeyError: "None of [DatetimeIndex(['2019-02-28', '2019-03-31',\n               '2019-04-30', '2019-05-31', '2019-06-30', '2019-07-31',\n               '2019-08-31', '2019-09-30', '2019-10-31', '2019-11-30',\n               '2019-12-31', '2020-01-31'],\n              dtype='datetime64[ns]', freq=None)] are in the [columns]"
这是我的密码:

# Libraries
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt

%matplotlib inline

df = pd.read_csv('tv-sales.csv', parse_dates=['Date'], index_col='Date')

df.info()

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 365 entries, 2019-02-01 to 2020-01-31
Data columns (total 6 columns):
 #   Column               Non-Null Count  Dtype  
---  ------               --------------  -----  
 0   Spend                365 non-null    float64
 1   Traffic              365 non-null    int64  
 2   Sales                365 non-null    int64  

# Resample to Months
df = df.resample('M').sum()

df.index

DatetimeIndex(['2019-02-28', '2019-03-31',
               '2019-04-30', '2019-05-31', '2019-06-30', '2019-07-31',
               '2019-08-31', '2019-09-30', '2019-10-31', '2019-11-30',
               '2019-12-31', '2020-01-31'],
              dtype='datetime64[ns]', name='Date', freq='M')

# Visualize

ax = df.plot(x=df.index.values, y='Spend', legend=False)
#库
作为pd进口熊猫
导入matplotlib
将matplotlib.pyplot作为plt导入
%matplotlib内联
df=pd.read\u csv('tv-sales.csv',parse\u dates=['Date'],index\u col='Date')
df.info()
日期时间索引:365个条目,2019-02-01至2020-01-31
数据列(共6列):
#列非空计数数据类型
---  ------               --------------  -----  
0花费365个非空浮点64
1流量365非空int64
2销售365非空int64
#重新采样至个月
df=df.resample('M').sum()
指数
日期时间索引(['2019-02-28','2019-03-31',',
'2019-04-30', '2019-05-31', '2019-06-30', '2019-07-31',
'2019-08-31', '2019-09-30', '2019-10-31', '2019-11-30',
'2019-12-31', '2020-01-31'],
dtype='datetime64[ns]',name='Date',freq='M')
#想象
ax=df.plot(x=df.index.values,y='Spend',legend=False)

使用
x=df.index.values
将导致错误,因为熊猫将尝试将
df.index.values
的值作为列获取

您可以使用
use\u index
将索引设置为x值:


df.plot(y='Spend',使用_index=True)
使用
x=df.index.values
将导致错误,因为熊猫会尝试将
df.index.values的值作为列获取

您可以使用
use\u index
将索引设置为x值:


df.plot(y='Spend',use_index=True)

您好,我在下面贴了一个答案,如果有帮助,请接受,谢谢。您好,我在下面贴了一个答案,如果有帮助,请接受,谢谢。