python - 在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
并通过by获得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
推荐阅读
- amazon-web-services - 拉取附加到 Amplify 的项目
- node.js - 如何列出节点 cron 的计划作业
- authentication - Google Analytics Embed API 403 错误请求的身份验证范围不足
- python - 如何在字符串中找到所有可能的连续三元组?
- javascript - 需要正则表达式来比较字符串中的最后一个数字
- php - 基于 Cookie 的身份验证 - 客户端
- github - 使用 github webhooks 配置成功/失败通知
- android - 如何在 Android 上实现应用内购买并处理一些逻辑以增加我的服务器上的积分?
- c - 在 while 循环中使用 scanf() 读取分段错误字符串
- android - 在 Jenkins 上上传 android 构建(.apk 文件)只是为了运行自动化套件而不是构建 android apk