Python - 创建具有发生百分比的图

Python - Create plot with percentage of occurence

我有一个包含订单的数据框。每个产品都有一种颜色。我想创建每月数据的(线)图并显示整个月的颜色出现情况。

当前数据框的片段:

                         Color 
2021-08-25 17:43:30      Blue
2021-08-25 17:26:34      Blue
2021-08-25 17:15:51      Green
2021-09-02 14:23:19      Blue
2021-09-04 18:11:17      Yellow

我想我需要先创建一个额外的列,其中包含整个月的发生百分比。我尝试使用:

df.groupby(['Color']).Color.agg([('Color_count', 'count')]).reset_index()

哪个给了我:

           Color       Color_count
0          Blue        2
1          Green       1

所需的输出应该给我包含所有颜色和每月出现百分比的列,例如:

                         Blue       Green      Yellow     
2021-08-31               0.73       0.24       0.00
2021-09-30               0.66       0.29       0.01

根据这些百分比,我可以绘制图表来显示每月的颜色数据。

提前致谢。

使用Grouper with SeriesGroupBy.value_counts and Series.unstack:

df1 = (df.groupby(pd.Grouper(freq='M'))['Color']
         .value_counts(normalize=True)
         .unstack(fill_value=0)
         .rename_axis(None, axis=1))
print (df1)
                Blue     Green  Yellow
2021-08-31  0.666667  0.333333     0.0
2021-09-30  0.500000  0.000000     0.5