Conditional Cumsum in pandas data-frame - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Conditional Cumsum in pandas data-frame (/thread-26410.html) |
Conditional Cumsum in pandas data-frame - klllmmm - Apr-30-2020 I'm trying to get a cumulative total if the code is equal to 100. df = pd.DataFrame(data = {'Code':[100,100,200,300,100], 'Value':[1000,1000,500,750,1000], 'Expected_Cum_100':[1000,2000,2000,2000,3000],})This was my try, but I couldn't get the expected result c = df["Value"].cumsum() df['Cum_100'] = c.mask(df["Code"] != 100).ffill() Appreciate it if anyone can suggest a way to get the expected cumulative total.
RE: Conditional Cumsum in pandas data-frame - klllmmm - May-01-2020 I managed to do this by creating an intermediary column as a new value. df['New_Value'] = df.apply(lambda x : x['Value'] if (x['Code'] == 100) else np.nan, axis=1) c = df['New_Value'].cumsum() df['Cum_100'] = c.mask(df["Code"] != 100).ffill() del ['New_Value']
|