links to " Stackoverflow question " I am new to Python and tried the program in the links however, I am getting the below error, am I missing anything here? Could you point me out?
...............................
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({
'weight':[1, 2, 3, 4],
'date':['2011-05-01', '2013-10-10', '2015-12-17', '2017-10-29']
})
df['date'] = pd.to_datetime(df['date'])
df1 = df.groupby(df['date'].dt.to_period('M')).sum()
df1 = df1.resample('M').asfreq().fillna(0)
plt.figure();
df1.plot(x='date', y='weight', kind='bar')
.......................................... Traceback (most recent call last):
File "/PycharmProjects/hellopython/hello_world", line 24, in
df1.plot(x='date', y='weight', kind='bar')
File "\PycharmProjects\hellopython\venv\lib\site-
packages\pandas\plotting_core.py", line 920, in call
elif not isinstance(data[x], ABCSeries):
File "\PycharmProjects\hellopython\venv\lib\site-packages\pandas\core\frame.py", line 3024, in getitem
indexer = self.columns.get_loc(key)
File "\PycharmProjects\hellopython\venv\lib\site-
packages\pandas\core\indexes\base.py", line 3082, in get_loc
raise KeyError(key) from err
KeyError: 'date'
Two options
Option 1
Since date
is as index, then we don't need to pass x and y axis to plot. Thanks to @Nk03 for suggesting this option.
Modified below line in existing code
df1.plot(kind='bar')
Code
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({
'weight':[1, 2, 3, 4],
'date':['2011-05-01', '2013-10-10', '2015-12-17', '2017-10-29']
})
df['date'] = pd.to_datetime(df['date'])
df1 = df.groupby(df['date'].dt.to_period('M')).sum()
df1 = df1.resample('M').asfreq().fillna(0)
plt.figure();
df1.plot(kind='bar')
Option 2 - Reset index
Added below line to existing code
df1 = df1.reset_index()
Complete code
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({
'weight':[1, 2, 3, 4],
'date':['2011-05-01', '2013-10-10', '2015-12-17', '2017-10-29']
})
df['date'] = pd.to_datetime(df['date'])
df1 = df.groupby(df['date'].dt.to_period('M')).sum()
df1 = df1.resample('M').asfreq().fillna(0)
df1 = df1.reset_index()
plt.figure();
df1.plot(x='date', y='weight', kind='bar')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.