Reputation: 55
I've got a dataframe which in general form looks like this.
A B C
0 1 2 3
1 2 4 6
2 3 5 7
I'd like to create another dataframe where in each value is the cumulative sum along the row of values in the original dataframe, starting from the right, rather than the left - i.e. the output should look like this:
A B C
0 6 5 3
1 12 10 6
2 ...
Can anyone suggest a bit of code to do this?
Upvotes: 2
Views: 803
Reputation: 863741
Use iloc
for reversing values twice:
df = df.iloc[:, ::-1].cumsum(axis=1).iloc[:, ::-1]
print (df)
A B C
0 6 5 3
1 12 10 6
2 15 12 7
#first reverse values
print (df.iloc[:, ::-1])
C B A
0 3 2 1
1 6 4 2
2 7 5 3
#then use function cumsum
print (df.iloc[:, ::-1].cumsum(axis=1))
C B A
0 3 5 6
1 6 10 12
2 7 12 15
#last reverse back
print (df.iloc[:, ::-1].cumsum(axis=1).iloc[:, ::-1])
A B C
0 6 5 3
1 12 10 6
2 15 12 7
Upvotes: 4