数据帧大熊猫中的总和百分比

itj*_*s18 3 python pandas

我通过使用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 
Run Code Online (Sandbox Code Playgroud)

我正在寻找创建一个排除'None'行的输出,并创建'bottom','top'和'mediocre'行的总和的百分比.欲望输出如下.

         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%
Run Code Online (Sandbox Code Playgroud)

我正在努力的一个主要部分是创建一个新的行来等于输出.任何帮助将不胜感激!

Mar*_*ius 10

您可以'None'像这样删除行:

df2 = df2.drop('None')
Run Code Online (Sandbox Code Playgroud)

如果您不希望它永久删除,则不必将结果分配回去 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
Run Code Online (Sandbox Code Playgroud)

要直接获得该结果而不永久删除该None行:

df2.drop('None').apply(lambda c: c / c.sum() * 100, axis=0)
Run Code Online (Sandbox Code Playgroud)

  • 无需通过`apply`; `100*df2/df2.sum()`应该有效. (3认同)