Skip to content Skip to sidebar Skip to footer

Pandas Cumsum On A Separate Column Condition

I have an issue using Pandas and cumsum which is not behaving as I was expecting so was wondering if anyone could shed some light on how this works. I have a dataframe that looks a

Solution 1:

Looks like you have most of what you want. If you want null values (NaN) for 0-flags then do this:

df['cum_sum'] = df[df['flag'] == 1]['price'].cumsum()

flag price cum_sum 0 1 2 2.0 1 1 5 7.0 2 1 8 15.0 3 0 9 NaN 4 0 12 NaN 5 1 2 17.0

Solution 2:

Is this what you want?

In [15]: df.price.mul(df.flag).cumsum().mul(df.flag)
Out[15]:
02172153040517
dtype: int64

Post a Comment for "Pandas Cumsum On A Separate Column Condition"