Reputation: 49
My dataframe has 20 columns and multiple rows. I want to calculate the percentage increase or decrease based on the previous column value but the same row. if a previous value is not available (in the first column) I want 100 in that place.
I have tried the shift(-1) method of pandas but it's not working.
Dataframe:
A B C D E F
10 20 25 50 150 100
100 130 195 150 250 250
Expected:
A B C D E F
100 100 25 100 200 -33
100 30 50 -23 66 0
Upvotes: 0
Views: 1102
Reputation: 150735
I suppose you can use shift(axis=1)
:
(df.diff(axis=1)/df.shift(axis=1) * 100 ).fillna(100).astype(int)
but I think it's easier doing so on transpose.
tmp_df = df.T
tmp_df = tmp_df.diff()/tmp_df.shift() * 100
tmp_df.fillna(100).astype(int).T
Output:
+----+------+------+-----+------+------+-----+
| | A | B | C | D | E | F |
+----+------+------+-----+------+------+-----+
| 0 | 100 | 100 | 25 | 100 | 200 | -33 |
| 1 | 100 | 30 | 50 | -23 | 66 | 0 |
+----+------+------+-----+------+------+-----+
Upvotes: 1