[英]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. 我的数据框有20列和多行。 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. 如果先前的值不可用(在第一列中),我希望该位置为100。
I have tried the shift(-1) method of pandas but it's not working. 我已经尝试过使用shift(-1)熊猫方法,但是它不起作用。
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)
: 我想你可以使用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 |
+----+------+------+-----+------+------+-----+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.