开发者

Pandas - how to aggregate values between 2 ranges in a specific column [duplicate]

This question already has answers here: Make Pandas groupby act similarly to itertools groupby (3 answers) Closed 10 mins ago.

I'm working on a df with 2 columns e.g.

column1 = [False, False, False, True, False, False, True]
column2 = [1, 1, 1, 1, 1, 1, 1]

I want to sum all "False" values until the first "True" value, and again sum t开发者_如何学JAVAhe following "False" values until the next "True" etc.

The output should be

column3 = [0,0,0,3,0,0,2]

I tried to sum column values but I can't "reset" the counter once hitting a "True" from a different column


You can use:

df['column3'] = (df['column2']
 .mask(df['column1']) # get False values only
 .groupby(df.loc[::-1, 'column1'].cumsum()) # group with next True
 # get sum of False values only where True
 .transform('sum').where(df['column1'], 0).convert_dtypes()
)

Output:

   column1  column2  column3
0    False        1        0
1    False        1        0
2    False        1        0
3     True        1        3
4    False        1        0
5    False        1        0
6     True        1        2


Use:

column1 = [False, False, False, True, False, False, True]
column2 = [1, 1, 1, 1, 1, 1, 1]

df = pd.DataFrame({'column1': column1,'column2':column2})

#create groups
s = (df['column1']).iloc[::-1].cumsum().iloc[::-1]

df['column3'] = (~df['column1']).groupby(s)
                   .transform('sum')
                   .mask(s.duplicated(keep='last'), 0)
print (df)
   column1  column2  column3
0    False        1        0
1    False        1        0
2    False        1        0
3     True        1        3
4    False        1        0
5    False        1        0
6     True        1        2

If need alo per groups by column2:

df1 = df.assign(g = df['column1'].iloc[::-1].cumsum().iloc[::-1],
                mask = ~df['column1'])

df['column3'] = (df1.groupby(['g','column2'])['mask']
                   .transform('sum')
                   .mask(df1.duplicated(subset=['g','column2'], keep='last'), 0))
print (df)
   column1  column2  column3
0    False        1        0
1    False        1        0
2    False        1        0
3     True        1        3
4    False        1        0
5    False        1        0
6     True        1        2
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜