Pandas rows multiple rows as one, adding specific column

Viewed 52
import pandas as pd 

training_data = pd.DataFrame()

training_data['a'] = [401,401.2,410,420,425,426, 426.1]
training_data['b'] = [1,1,2,2,2,3,3]

training_data['condition'] = [True, False, True, True, True,False, False]

My training data:

a         b      condition
401       1        True
401.2     1        False
410       2        True
420       2        True
425       2        True
426       3        False
426.1     3        False

Desired output:

a         b      condition
401       2        True         (1+1)

410       2        True
420       2        True
425       8        True        (2+3+3)

All False conditions have been deleted and column 'b' has been added with the amended values.

How can I get this desired output?

I am aware of using .cumsum() with

training_data.query('condition').groupby('grp').agg()
1 Answers

Here we go with cumsum

out = training_data.groupby(training_data['condition'].cumsum()).agg({'a':'first','b':'sum','condition':'first'})
Out[271]: 
               a  b  condition
condition                     
1          401.0  2       True
2          410.0  2       True
3          420.0  2       True
4          425.0  8       True
Related