pandas :按移位分组和累加和(GroupBy Shift And Cumulative Sum) [英] Pandas: GroupBy Shift And Cumulative Sum

查看:28
本文介绍了 pandas :按移位分组和累加和(GroupBy Shift And Cumulative Sum)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做groupbyshiftcumsum,这看起来相当琐碎的任务,但我仍然对得到的结果头晕目眩。有没有人能告诉我我做错了什么。我在网上找到的所有结果都显示出与我正在做的事情相同或相同的变化。下面是我的实现。

temp = pd.DataFrame(data=[['a',1],['a',1],['a',1],['b',1],['b',1],['b',1],['c',1],['c',1]], columns=['ID','X'])

temp['transformed'] = temp.groupby('ID')['X'].cumsum().shift()
print(temp)

   ID   X   transformed
0   a   1   NaN
1   a   1   1.0
2   a   1   2.0
3   b   1   3.0
4   b   1   1.0
5   b   1   2.0
6   c   1   3.0
7   c   1   1.0

这是错误的,因为我要查找的实际内容或内容如下:

   ID   X   transformed
0   a   1   NaN
1   a   1   1.0
2   a   1   2.0
3   b   1   NaN
4   b   1   1.0
5   b   1   2.0
6   c   1   NaN
7   c   1   1.0

事先非常感谢。

推荐答案

您可以使用transform()将在groupby的每个级别创建的单独组馈送到cumsum()shift()方法中。

temp['transformed'] = 
    temp.groupby('ID')['X'].transform(lambda x: x.cumsum().shift())
  ID  X   transformed
0  a  1   NaN
1  a  1   1.0
2  a  1   2.0
3  b  1   NaN
4  b  1   1.0
5  b  1   2.0
6  c  1   NaN
7  c  1   1.0

有关transform()的更多信息,请查看此处:

这篇关于 pandas :按移位分组和累加和(GroupBy Shift And Cumulative Sum)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆