gpt4 book ai didi

python-3.x - Pandas:GroupBy Shift 和 Cumulative Sum

转载 作者:行者123 更新时间:2023-12-04 18:00:48 29 4
gpt4 key购买 nike

我想做 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() 的更多信息,请参见此处:
  • https://jakevdp.github.io/PythonDataScienceHandbook/03.08-aggregation-and-grouping.html#Transformation
  • https://pandas.pydata.org/pandas-docs/version/0.22/groupby.html#transformation
  • 关于python-3.x - Pandas:GroupBy Shift 和 Cumulative Sum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54993050/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com