数据框中总和的百分比

3 投票
1 回答
4569 浏览
提问于 2025-04-18 02:44

我使用pandas库里的melt和groupby功能,结合值和变量,创建了一个数据框。具体代码是:

df2 = pd.melt(df1).groupby(['value','variable'])['variable'].count().unstack('variable').fillna(0)

         Percentile     Percentile1     Percentile2     Percentile3
value                                               
None          0             16              32              48
bottom        0             69              85              88  
top           0             69              88              82  
mediocre     414           260             209             196 

我想要的输出结果是去掉'None'这一行,并计算'底部'、'顶部'和'中等'这几行的总和所占的百分比。理想的输出结果应该是这样的。

         Percentile     Percentile1     Percentile2     Percentile3
value                                               
bottom        0%          17.3%             22.3%              24.0%    
top           0%          17.3%             23.0%              22.4%    
mediocre     414%         65.3%             54.7%              53.6%

我现在遇到的主要问题之一是如何创建一个新行来显示这个输出。任何帮助都会非常感激!

1 个回答

10

你可以这样去掉 'None' 这一行:

df2 = df2.drop('None')

如果你不想永久性地去掉这一行,就不需要把结果再赋值给 df2

然后你可以用下面的方式得到你想要的结果:

df2.apply(lambda c: c / c.sum() * 100, axis=0)
Out[11]: 
          Percentile1  Percentile2  Percentile3
value                                          
bottom      17.336683    22.251309    24.043716
top         17.336683    23.036649    22.404372
mediocre    65.326633    54.712042    53.551913

如果你想直接得到这个结果,而不想永久性地去掉 None 这一行,可以这样做:

df2.drop('None').apply(lambda c: c / c.sum() * 100, axis=0)

撰写回答