本文介绍了如何在Pandas的群组中使用cumsum?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

df = pd.DataFrame.from_dict({'id': ['A', 'B', 'A', 'C', 'D', 'B', 'C'], 'val': [1,2,-3,1,5,6,-2], 'stuff':['12','23232','13','1234','3235','3236','732323']})

  id   stuff  val
0  A      12    1
1  B   23232    2
2  A      13   -3
3  C    1234    1
4  D    3235    5
5  B    3236    6
6  C  732323   -2

我想为每个id运行一些val,所以所需的输出如下所示:

I'd like to get running some of val for each id, so the desired output looks like this:

  id   stuff  val  cumsum
0  A      12    1   1
1  B   23232    2   2
2  A      13   -3   -2
3  C    1234    1   1
4  D    3235    5   5
5  B    3236    6   8
6  C  732323   -2  -1

这是我尝试过的:

df['cumsum'] = df.groupby('id').cumsum(['val'])

df['cumsum'] = df.groupby('id').cumsum(['val'])

这是我得到的错误:

ValueError: Wrong number of items passed 0, placement implies 1

推荐答案

您可以致电 transform 并传递 cumsum 函数将该列添加到您的df中:

You can call transform and pass the cumsum function to add that column to your df:

In [156]:
df['cumsum'] = df.groupby('id')['val'].transform(pd.Series.cumsum)
df

Out[156]:
  id   stuff  val  cumsum
0  A      12    1       1
1  B   23232    2       2
2  A      13   -3      -2
3  C    1234    1       1
4  D    3235    5       5
5  B    3236    6       8
6  C  732323   -2      -1

关于您的错误,您不能在Series groupby对象上调用cumsum,其次,您将列名作为无意义的列表传递.

With respect to your error, you can't call cumsum on a Series groupby object, secondly you're passing the name of the column as a list which is meaningless.

这可行:

In [159]:
df.groupby('id')['val'].cumsum()

Out[159]:
0    1
1    2
2   -2
3    1
4    5
5    8
6   -1
dtype: int64

这篇关于如何在Pandas的群组中使用cumsum?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-03 17:43