python - 使用 Pandas groupby 数据帧中的第一行计算累积差异

标签 python pandas

我有以下基于每日数据的分组数据框

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/

相关文章:

Python:如何按原样强制字符串文字而不被解释为正则表达式模式

python - 我如何报告在整个脚本中从未匹配的任何正则表达式?

python - 在中间逗号处将字符串一分为二?

python - flask 蓝图属性错误 : 'module' object has no attribute 'name' error

python - 如何在数据框中批量滞后列

python - 将列转换为标题行

python - AND 感知器的权重和偏差是多少?

python - 为什么本地启动的线程不会在每次迭代结束时终止?

python - 如何更改数据框中保存的数据的格式?

python - pandas dataframe hexbin 图没有 xlabel 或轴值