Python使用Pandas绘制月度平均价格图及KeyError: 'month'报错解决
错误原因
你的代码存在4个核心问题:
- 价格字段去除
$符号后仍为字符串类型,无法直接计算平均值 - 分组维度错误:计算月均价格需要按
month字段分组,你错误使用了date字段分组 - 聚合方法错误:pandas 中计算平均值的方法为
mean(),不存在avg()方法 - 直接取
month的唯一值未做排序,会导致趋势图横轴顺序混乱
修正后的完整代码
import pandas as pd import matplotlib.pyplot as plt 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).astype(float) df['date'] = pd.to_datetime(df['date']) df['month'], df['year'] = df.date.dt.month, df.date.dt.year # 按月份分组计算平均价格,同时对月份排序 monthly_avg = df.groupby('month', as_index=False)['price'].mean().sort_values('month') # 绘图 plt.plot(monthly_avg['month'], monthly_avg['price']) plt.xlabel('Month') plt.ylabel('Average Price') plt.title('Monthly Average Price Trend') plt.show()
效果说明
运行上述代码即可生成你预期的月度平均价格趋势图,6月平均价格为(90+20)/2=55,8月为80,9月为79,趋势和预期效果完全一致。
内容的提问来源于stack exchange,提问作者Test
相关产品推荐
相关产品推荐

