简体   繁体   English

根据熊猫数据框中同一行的上一列值计算增加或减少的百分比

[英]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.

相关问题 Python Pandas Dataframe 根据同一列中的前一行值计算新行值 - Python Pandas Dataframe calculating new row value based on previous row value within same column 如何根据计算的同一列中的先前值计算 pandas 列? - How to calculate a pandas column based on the previous value in the same column that is calculated? 检查数据框中的值是否会增加或减少一定的百分比 - Check if a value in dataframe will increase or decrease a certain percentage 基于列值的百分比减少 - Percentage decrease based on column value 找到一列熊猫数据框的增加,减少 - Find the increase, decrease in a column of pandas Dataframe 根据前一行值对 Pandas Dataframe 进行排序 - Sort Pandas Dataframe based on previous row value 熊猫-根据先前计算的行值计算行值 - Pandas - calculate row value based on previous calculated row value 如何从熊猫数据框中获取同一行(上一列)的上一个值? - How to get the previous value of the same row (previous column) from the pandas dataframe? Pandas Dataframe基于前一行,将值添加到新列,但该列的最大值限于该列 - Pandas Dataframe Add a value to a new Column based on the previous row limited to the maximum value in that column 如果只能在pandas数据框中使用它之后才能声明该列,则如何使用该列的前一行值进行计算? - How to calculate with previous row value of a column if it can be declared only after it should be used in pandas dataframe?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM