Pandas: GroupBy Shift And Cumulative Sum( pandas :按移位分组和累加和(GroupBy Shift And Cumulative Sum))
本文介绍了 pandas :按移位分组和累加和(GroupBy Shift And Cumulative Sum)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想做groupby、shift和cumsum,这看起来相当琐碎的任务,但我仍然对得到的结果头晕目眩。有没有人能告诉我我做错了什么。我在网上找到的所有结果都显示出与我正在做的事情相同或相同的变化。下面是我的实现。
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()的更多信息,请查看此处:
- https://jakevdp.github.io/PythonDataScienceHandbook/03.08-aggregation-and-grouping.html#Transformation
- https://pandas.pydata.org/pandas-docs/version/0.22/groupby.html#transformation
这篇关于 pandas :按移位分组和累加和(GroupBy Shift And Cumulative Sum)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:pandas :按移位分组和累加和(GroupBy Shift And Cumulative Sum)
基础教程推荐
猜你喜欢
- Discord.py 缺少必需的参数 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
