【发布时间】:2021-12-17 04:49:07
【问题描述】:
我有问题。我有一个数据框(请参见下文)。其中包含价格和日期。我想显示每个月的平均价格。我怎么能这样做?我试过了,但我得到了以下错误KeyError: 'month'。如何绘制如下图?
listing_id date price month year
0 1 2021-09-07 79.00 9 2021
1 2 2021-08-07 80.00 8 2021
2 3 2021-06-07 90.00 6 2021
3 4 2021-06-05 20.00 6 2021
d = {'listing_id': [1, 2, 3, 4],
'date': ['2021-09-07', '2021-08-07', '2021-06-07', '2021-06-05'],
'price': ['$79.00', '$80.00', '$90.00', '$20.00']}
df = pd.DataFrame(data=d)
df['price'] = df['price'].str.replace('$', '', regex=False)
df['date'] = pd.to_datetime(df['date'])
df['month'], df['year'] = df.date.dt.month, df.date.dt.year
print(df)
x = df['month'].unique()
y = df.groupby('date').avg()[['price']]
plt.plot(x,y)
plt.show()
KeyError: 'month'
【问题讨论】:
-
df.groupby('month')['price'].mean().plot() -
在绘图之前不要忘记将
price转换为浮点数 -
它应该是条形图而不是线图。
df.groupby('month')['price'].mean().plot(kind='bar', rot=0) -
根据@QuangHoang
df['price'] = df['price'].str.replace('$', '', regex=False).astype(float)
标签: python pandas dataframe matplotlib