[英]Pandas Dataframe cumsum function to “restart” when value in row changes
df['total'] = (df.DR - df.CR).cumsum()
is giving:正在给:
...
Name DR CR total
303 B3 46.80 0.00 46682.07
304 B3 45.20 0.00 46727.27
395 BS1 0.00 10.37 47905.31
396 BS2 0.00 87.00 47818.31
397 C 0.00 482.10 47336.21
399 C 20.00 0.00 47356.21
However I would like the cumsum to "restart" whenever the "Name"
column (B3,BS1,C) changes to a different value.但是,每当
"Name"
列(B3,BS1,C)更改为不同的值时,我希望 cumsum “重新启动”。
So the desired result is:所以想要的结果是:
Name DR CR total
303 B3 46.80 0.00 46.80
304 B3 45.20 0.00 1.60
395 BS1 0.00 10.37 -10.37
396 BS2 0.00 87.00 -97.37
397 C 0.00 482.10 -482.10
399 C 20.00 0.00 -462.10
I am new to pandas.我是 pandas 的新手。 Thanks for your help
谢谢你的帮助
I have tried things like, but not working: df['total'] = df.groupby('GL')[(df.DR - df.CR)].cumsum()
我已经尝试过,但没有工作:
df['total'] = df.groupby('GL')[(df.DR - df.CR)].cumsum()
First variant - if you want to "join" all rows for each Name into a single group:第一个变体- 如果您想将每个名称的所有行“加入”到一个组中:
df['total'] = df.groupby('Name').apply(lambda grp:
(grp.DR - grp.CR).cumsum()).reset_index(level=0, drop=True)
For your source data the result is:对于您的源数据,结果是:
Name DR CR total
303 B3 46.8 0.00 46.80
304 B3 45.2 0.00 92.00
395 BS1 0.0 10.37 -10.37
396 BS1 0.0 87.00 -97.37
397 C 0.0 482.10 -482.10
399 C 20.0 0.00 -462.10
Second variant - if any change in Name is to start a new group.第二种变体- 如果名称的任何更改是开始一个新组。
Assume that your DataFrame contains:假设您的 DataFrame 包含:
Name DR CR
303 B3 46.8 0.00
304 B3 45.2 0.00
395 BS1 0.0 10.37
396 BS1 0.0 87.00
397 C 0.0 482.10
399 C 20.0 0.00
400 B3 53.0 8.00
401 B3 40.8 6.15
and the second B3 group is to be summed separately from the first group:第二个B3组将与第一组分开求和:
df['total'] = df.groupby((df.Name != df.Name.shift()).cumsum())\
.apply(lambda grp: (grp.DR - grp.CR).cumsum()).reset_index(level=0, drop=True)
getting:得到:
Name DR CR total
303 B3 46.8 0.00 46.80
304 B3 45.2 0.00 92.00
395 BS1 0.0 10.37 -10.37
396 BS1 0.0 87.00 -97.37
397 C 0.0 482.10 -482.10
399 C 20.0 0.00 -462.10
400 B3 53.0 8.00 45.00
401 B3 40.8 6.15 79.65
As you can see, the second B3 group is summed separately.如您所见,第二个B3组是单独相加的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.