首页 > 解决方案 > 在Python中按阈值计算和计算每列的百分比

问题描述

如果我有以下数据框:

studentId   sex     history    english    math    biology
    01      male       75         90       85        60
    02     female      85         80       95        70
    03      male       55         60       78        86
    04      male       90         89       76        80  

我想要一个新表格,显示每个科目分数高于阈值 80(包括 80)的百分比。例如,有两个学生的历史分数高于80,那么历史的百分比是2/4 = 50%。有人可以帮助我用 Python 做到这一点吗?谢谢。

history        50%
english        75% 
math           50%
biology        50%

标签: pythonpandas

解决方案


采用:

s = df.iloc[:, 2:].ge(80).mean().mul(100)
print (s)
history    50.0
english    75.0
math       50.0
biology    50.0
dtype: float64

说明

首先按以下位置仅选择必要的列DataFrame.iloc

print (df.iloc[:, 2:])
   history  english  math  biology
0       75       90    85       60
1       85       80    95       70
2       55       60    78       86
3       90       89    76       80

然后用DataFrame.ge( >=) 比较:

print (df.iloc[:, 2:].ge(80))
   history  english   math  biology
0    False     True   True    False
1     True     True   True    False
2    False    False  False     True
3     True     True  False     True

并通过by获得mean多个:100DataFrame.mul

print (df.iloc[:, 2:].ge(80).mean().mul(100))
history    50.0
english    75.0
math       50.0
biology    50.0
dtype: float64

推荐阅读