3

Is there a more elegant way to achieve this? my current solution based on various stackoverflow answers is as following

df = pds.DataFrame([[11,12,13,14],[15,16,17,18]], columns = [0,1,2,3])  
print df  
dT = df.T  
dT.reindex(dT.index[::-1]).cumsum().reindex(dT.index).T  

Output

df is:
    0   1   2   3  
0  11  12  13  14  
1  15  16  17  18  

after by row reverse cumsum
    0   1   2   3
0   50  39  27  14  
1   66  51  35  18  

I have to perform this often on my data (much bigger size also), and try to find out a short/better way to do achieve this.

Thanks

1 Answer 1

6

Here is a slightly more readable alternative:

df[df.columns[::-1]].cumsum(axis=1)[df.columns]

There is no need to transpose your DataFrame; just use the axis=1 argument to cumsum.

Obviously the easiest thing would be to just store your DataFrame columns in the opposite order, but I assume there is some reason why you're not doing that.

1
  • Thanks for the simplification. indeed I need to do both forward cumulation and reverse cumulation, and also maintain the original column order for other parts of the analysis. Oct 15, 2014 at 19:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.