我有以下基于每日数据的分组数据框
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
在第一个级别上,并且通过调用调用从返回的系列中减去BookLevel transform
,first
那么我们可以将其添加为新的所需列:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句