cph*_*ill 3 python matplotlib pandas
我获取了一些每日日期格式的 csv 数据,并将该数据重新采样为每月数据,现在想要使用 matplotlib 进行可视化。但是,当我尝试绘制重新采样的时间序列数据时,我遇到了以下错误,并且不确定如何继续。我尝试参考两者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]"
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
# 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)
Run Code Online (Sandbox Code Playgroud)
使用x=df.index.values会导致错误,因为 pandas 会尝试获取df.index.values列的值。
您可以使用use_index将索引设置为 x 值:
df.plot(y='Spend', use_index=True)
| 归档时间: |
|
| 查看次数: |
2546 次 |
| 最近记录: |