首页 > 解决方案 > 数据框行之间的计算

问题描述

我在 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

这看起来非常混乱,并且没有明确的班级排名。是否有可能一次获得每个团队的分数,而无需从一个数据帧跳到另一个数据帧,而且还有一种更清晰地显示它的方法?

标签: pythonpandasdataframe

解决方案


[编辑]让我们有一个可重现的例子:

将原始数据复制到 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

推荐阅读