Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:将cumsum和product应用于pandas groupby_Python_Pandas - Fatal编程技术网

Python:将cumsum和product应用于pandas groupby

Python:将cumsum和product应用于pandas groupby,python,pandas,Python,Pandas,我有一个包含LTD和CycleCount列的熊猫数据框架,需要像这样填充CycleSum列: LTD CycleCount CycleSum 1/1/2017 1 1 1/1/2017 1 1 2/1/2017 0 1 2/1/2017 0 1 3/1/2017 1 2 3/1/2017 1 2

我有一个包含LTD和CycleCount列的熊猫数据框架,需要像这样填充CycleSum列:

LTD         CycleCount    CycleSum
1/1/2017    1             1
1/1/2017    1             1
2/1/2017    0             1
2/1/2017    0             1
3/1/2017    1             2
3/1/2017    1             2
4/1/2017    1             3
4/1/2017    1             3
我试着做:

df['CycleSum']=df.groupby('LTD')['CycleCount'].prod()
要在CycleCount中获得具有1/0值的unique LTD,这是我的第一步,因为我得到了一个组:

LTD         CycleCount
1/1/2017    1
2/1/2017    0
3/1/2017    1
4/1/2017    1
但我找不到一种方法,如何在这个组上生成一个累积和,然后将其转换回原始数据帧

CycleCount只能为1或0,且每个有限公司的CycleCount相同。但对于CycleCount=1的任何不同有限公司,CycleSum必须增加 在Excel中很容易做到,但在Python中很难实现

有什么建议吗?一次行动的目的


PS我以前是VBA开发人员,可能这是一个noob案例,但要摆脱Excel逻辑是非常困难的。

执行
groupby
+
prod
然后执行
cumsum
然后加入

df.join(df.groupby('LTD').CycleCount.prod().cumsum().rename('CycleSum'), on='LTD')

         LTD  CycleCount  CycleSum
0 2017-01-01           1         1
1 2017-01-01           1         1
2 2017-02-01           0         1
3 2017-02-01           0         1
4 2017-03-01           1         2
5 2017-03-01           1         2
6 2017-04-01           1         3
7 2017-04-01           1         3

这些也会产生同样的结果

df.join(df.groupby('LTD').CycleCount.all().cumsum().rename('CycleSum'), on='LTD')
df.join(df.groupby('LTD').CycleCount.max().cumsum().rename('CycleSum'), on='LTD')

         LTD  CycleCount  CycleSum
0 2017-01-01           1         1
1 2017-01-01           1         1
2 2017-02-01           0         1
3 2017-02-01           0         1
4 2017-03-01           1         2
5 2017-03-01           1         2
6 2017-04-01           1         3
7 2017-04-01           1         3

非常感谢。这正是我要找的!