简体   繁体   中英

Calculate the percentage increase or decrease based on the previous column value of the same row in pandas dataframe

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

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 |
+----+------+------+-----+------+------+-----+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM