如何使用groupby按日历月显示标准偏差并进行绘图?

2024-05-28 19:10:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的数据集(df)基于鳄梨价格数据集,可在下面找到:

https://www.kaggle.com/neuromusic/avocado-prices

我试图绘制鳄梨的价格波动(标准差),按年份、月份和鳄梨类型,如下图所示

Price Volatility Chart

我试着这样编码,但我一直得到错误“value”必须是str或bytes的实例,而不是float:

month_dict = {1 : 'Jan', 
          2: 'Feb', 
          3: 'Mar', 
          4: 'Apr', 
          5: 'May', 
          6: 'Jun', 
          7: 'Jul', 
          8: 'Aug', 
          9: 'Sep', 
          10: 'Oct', 
          11: 'Nov', 
          12: 'Dec'}

cal_years =[2015, 2016, 2017]
types = ['conventional','organic']
df['Month'] = pd.to_datetime(df.index).month
fig, ax = plt.subplots(2,3, figsize=(15,10), sharey=True)
for type in types:
    for axy in range(2):
        for axx in range(3):            
                df_plot = df[(df['type'] == types[axy]) & (df['year'] == cal_years[axx])]
                df_plot = df_plot.groupby('Month', as_index=False)['AveragePrice'].std()                
                df_plot['Month'] = df_plot['Month'].map(month_dict)                
                ax[axy, axx].plot('Month','AveragePrice',data=df_plot, color='blue',marker='o')
                ax[axy, axx].set_title(str(cal_years[axx]) + ' ' + types[axy])
                ax[axy, axx].tick_params(axis='x', rotation=45)
fig.suptitle('Season price fluctuation', size=16)

如果有人能指出为什么代码没有像我预期的那样工作,我将不胜感激。非常感谢


Tags: 数据indfforplot价格axcal

热门问题