【问题标题】:Python - Create plot with percentage of occurencePython - 创建具有发生百分比的图
【发布时间】:2021-11-26 09:56:21
【问题描述】:

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

当前数据帧的一个sn-p:

                         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

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

提前谢谢你。

【问题讨论】:

    标签: python pandas pandas-groupby


    【解决方案1】:

    GrouperSeriesGroupBy.value_countsSeries.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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-21
      • 2016-03-14
      • 2018-07-07
      • 2020-07-03
      相关资源
      最近更新 更多