Reputation: 11
I am new to pandas and I was wondering if there was a way I could run formulas on two dataframes.
I have two dfs that have the same columns and same index. example each df looks like this
x y z
a 2 4 5
b 7 9 0
I want to take df1, df2 and find the absolute difference for x ,y, z something like (df1[n]-df2[n] / df1[n]) * 100 for each n element of columns, and store the result in a new df.
Note: I just want the difference to be positive. (Misunderstood the meaning of absolute)
Upvotes: 1
Views: 5585
Reputation: 79
If you use the formula you provided ((df1[n]-df2[n] / df1[n]) * 100
), you will get different results. You can use the Pandas abs
method: https://docs.python.org/3/library/functions.html#abs
Some examples:
a = {'x': [2], 'y': [4], 'z': [5]}
b = {'x': [7], 'y': [9], 'z': [0]}
df1 = pd.DataFrame(a)
df2 = pd.DataFrame(b)
df_abs = abs(df1 - df2) # Absolute difference
df_abs = (df1 - df2 / df1) * 100 # Different results
Upvotes: 1
Reputation: 14124
Yes run them as you wrote them
absolute
(df1 - df2).abs()
or
(df1 -df2).div(df2) * 100
Upvotes: 1