我有以下基于每日数据的分组数据框
Studentid Year Month BookLevel
JSmith 2015 12 1.4
2016 1 1.6
2 1.8
3 1.2
4 2.0
MBrown 2016 1 3.0
2 3.2
3 3.6
我想计算每个 Studentid 与 BookLevel 起点的差值。当前的 BookLevel 是根据 GroupBy 进行的 .max 计算,用于获取每个学生每月的最高 bookLevel
我正在寻找的是这样的:
Studentid Year Month BookLevel Progress Since Start
JSmith 2015 12 1.4 0 (or NAN)
2016 1 1.6 .2
2 1.8 .4
3 1.2 -.2
4 2.0 .6
2016 1 3.0 0 (or NAN)
MBrown 2 3.2 .2
3 3.6 .6
我是 Python/Pandas 的新手,并且尝试了很多方法,但没有任何方法可以接近。
最佳答案
好的,这应该可行,如果我们在第一级上groupby
,并从使用first
调用transform
返回的系列中减去BookLevel,那么我们可以将其添加为新的所需列:
In [47]:
df['ProgressSinceStart'] = df['BookLevel'] - df.groupby(level='Studentid')['BookLevel'].transform('first')
df
Out[47]:
BookLevel ProgressSinceStart
Studentid Year Month
JSmith 2015 12 1.4 0.0
2016 1 1.6 0.2
2 1.8 0.4
3 1.2 -0.2
4 2.0 0.6
MBrown 2016 1 3.0 0.0
2 3.2 0.2
3 3.6 0.6
关于python - 使用 Pandas groupby 数据帧中的第一行计算累积差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37634786/