how to groupby but counsecutively only

Viewed 31

i have a dataframe like this:

data = {'costs': [150, 400, 300, 500, 350], 'month':[1, 2, 2, 1, 1]}

df = pd.DataFrame(data)

i want to use groupby(['month']).sum() but first row not to be cobmined with fourth and fifth rows so the result of costs would be like this

list(df['costs'])= [150, 700, 850]
1 Answers

Try:

x = (
    df.groupby((df.month != df.month.shift(1)).cumsum())
    .agg({"costs": "sum", "month": "first"})
    .reset_index(drop=True)
)

print(x)

Prints:

   costs  month
0    150      1
1    700      2
2    850      1
Related