簡體   English   中英

在Python中按閾值計算和計算每列的百分比

[英]count and calculate percentage of each column by threshold in 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%

采用:

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多由100通過DataFrame.mul

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM