Search code examples
pandasdataframedata-sciencedata-munging

pandas dataframe how to sum all value of bigger columns per row


I have a dataframe:

0.  1. 2. 3
2.  3. 5. 9
5.  1. 0. 3

And for columns 1,2,3 - I want the value for each row to be the sum of higher columns So the new df will be:

0. 1. 2. 3 
2. 17 14. 9
5. 4. 3. 3

What is the best way to do so?


Solution

  • Let us try cumsum along axis=1 after reverting the columns 1, 2, 3:

    c = [1, 2, 3]
    df.loc[:, c] = df.loc[:, c[::-1]].cumsum(axis=1)
    

       0   1   2  3
    0  2  17  14  9
    1  5   4   3  3