在Python中按阈值计算和计算每一列的百分比

时间:2018-08-30 13:09:42

标签: python pandas

如果我具有以下数据框:

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%

1 个答案:

答案 0 :(得分:8)

使用:

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

然后将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

src/main/web-app/WEB-INF
相关问题