首页 > 解决方案 > 根据条件或值计算列中值的百分比

问题描述

我有下面的表格,我想获得 >= 10 秒或更长时间的每种类型的 %。什么是有效的模块化代码?我通常只会过滤每种类型然后除以,但想知道是否有更好的方法来计算类型列中每个值的百分比 >= 10 秒或更多。

谢谢

   Type | Seconds
     A       23
     V       10
     V       10
     A       7
     B       1
     V       10
     B       72
     A       11
     V       19
     V        3



expected output:

    type   %
     A    .67
     V    .80
     B    .50

标签: pythonpython-3.xpandas

解决方案


一个稍微更有效的选择是创建一个布尔掩码Seconds.ge(10)groupby.mean()在掩码上使用:

df.Seconds.ge(10).groupby(df.Type).mean().reset_index(name='%')

#    Type         %
# 0     A  0.666667
# 1     B  0.500000
# 2     V  0.800000

时间比较

鉴于这些功能:

mask_groupby_mean = lambda df: df.Seconds.ge(10).groupby(df.Type).mean().reset_index(name='%')
groupby_apply = lambda df: df.groupby('Type').Seconds.apply(lambda x: (x.ge(10).sum() / len(x)) * 100).reset_index(name='%')
set_index_mean = lambda df: df.set_index('Type').ge(10).mean(level=0).rename(columns={'Seconds': '%'}).reset_index()

推荐阅读