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)
基础教程推荐
猜你喜欢
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 包装空间模型 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
