根据pandas数据框中同一行的前一列值计算增加或减少的百分比 [英] Calculate the percentage increase or decrease based on the previous column value of the same row in pandas dataframe
本文介绍了根据pandas数据框中同一行的前一列值计算增加或减少的百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据框有 20 列和多行.我想根据前一列值但同一行计算增加或减少的百分比.如果以前的值不可用(在第一列中),我希望在那个地方有 100.
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.
我尝试过 pandas 的 shift(-1) 方法,但它不起作用.
I have tried the shift(-1) method of pandas but it's not working.
数据框:
A B C D E F
10 20 25 50 150 100
100 130 195 150 250 250
预期:
A B C D E F
100 100 25 100 200 -33
100 30 50 -23 66 0
推荐答案
我想你可以使用 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
输出:
+----+------+------+-----+------+------+-----+
| | A | B | C | D | E | F |
+----+------+------+-----+------+------+-----+
| 0 | 100 | 100 | 25 | 100 | 200 | -33 |
| 1 | 100 | 30 | 50 | -23 | 66 | 0 |
+----+------+------+-----+------+------+-----+
这篇关于根据pandas数据框中同一行的前一列值计算增加或减少的百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文