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

瘦欲@ 提交于 2019-12-11 19:39:03

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/56013697/calculate-the-percentage-increase-or-decrease-based-on-the-previous-column-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!