python - 数据框行之间的计算
问题描述
我在 SQL 中做过类似的事情,而且相当简单,但我不知道如何在 Python 中做到这一点。我有一个看起来像这样的数据框:
Student Class Result Exam
a First Bad t1
a First Bad t2
a First Good t2
b Second Bad t1
c First Good t3
c First Bad t2
d Third Bad t1
d Third Bad t4
d Third Good t4
e Fourth Good t3
e Fourth Good t2
f Third Good t1
g Fourth Good t4
g Fourth Bad t3
一个学生只能在一个班级。一个学生可以多次参加考试,并获得不同的分数(顺序不是按时间顺序排列的,所以我并不关心他们参加什么考试)。目标是找出某些类是否比其他类执行得更好。
为此,我的想法是转换每个学生的好答案和坏答案的数量,计算一个类似 的分数score = good/(good+bad)
,然后再次平均:
Student Class Score ClassScore
a First 0.33 0.415
b Second 0 0
c First 0.5 0.415
d Third 0.33 0.665
e Fourth 1 0.75
f Third 1 0.665
g Fourth 0.5 0.75
这看起来非常混乱,并且没有明确的班级排名。是否有可能一次获得每个团队的分数,而无需从一个数据帧跳到另一个数据帧,而且还有一种更清晰地显示它的方法?
解决方案
[编辑]让我们有一个可重现的例子:
将原始数据复制到 data.txt 文件。
df = pd.read_csv('data.txt', sep='\s+')
答案:
# first line simplifies the rest of the expression
df['result_bin'] = df['Result'] == 'Good'
df.groupby(['Class', 'Student'])['result_bin'].mean().groupby('Class').mean()
这将返回:
Class
First 0.416667
Fourth 0.750000
Second 0.000000
Third 0.666667
推荐阅读
- regex - 使用 Regex 在 Visual Studio Code 中每次出现的末尾添加一个短语以开头且不结尾且不包含特殊符号
- linux - Pepper 机器人之旅 - 智能导航
- angular - Angular Ionic3 TypeScript - 从数组拼接后“TypeError:无法读取未定义的属性'名称'”
- apache-spark - 如何在 pyspark 中保留 HIVE 表顺序?
- python - 应用函数但记住索引位置
- javascript - PHP:如果在输入中检测到错误,则重新加载引导模式表单
- c - C程序:当我使用malloc函数时,我发现字节数总是比数组的大小多
- sql - 需要一种方法来确定 getdate() 是否在 SQL 的特定季节之间
- python - pyspark - kafka 集成:缺少库
- javascript - 为什么没有部署firebase函数onCall?