PV8
PV8

Reputation: 6270

Calculate change / deviation between two column values (in percent)?

i have a smiliar question to a lot of questions who are around here already: How to check change between two values (in percent)?

Python calculate new column where value is by subtracting the previous date price

I have a dataframe where i want to calculate a percentage deviation between two columns for every row:

A  B   diff_var
1  1    0%
1  2    100%

...

The problem is value A and B can have every number from -,0,+ and every combination is possible (e.g. A is negativ, B is positiv and so on). How can I make sure that I use the right calculation for it? And is there a function in python for it?

Upvotes: 1

Views: 276

Answers (1)

Mustafa Aydın
Mustafa Aydın

Reputation: 18306

Subtracting the B column from A and dividing by B gives the relative difference. Then you can multiply by 100 and add "%":

df["diff_var"] = df.B.sub(df.A).div(df.A).mul(100).astype(str).add("%")

to get

>>> df

   A  B diff_var
0  1  1     0.0%
1  1  2   100.0%

Upvotes: 1

Related Questions