1

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)

2 Answers 2

1

Yes run them as you wrote them

absolute

(df1 - df2).abs()

or

(df1 -df2).div(df2) * 100

Sign up to request clarification or add additional context in comments.

Comments

1

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 

2 Comments

Another use of the abs method is provided by @Kenan: (df1 - df2).abs()
I would suggest update link. You are using abs(df1 - df2) in answer which is python built-in function abs but you gave link of pandas.DataFrame.abs in description. and when you use (df1 - df2).abs() then actually you are using pandas.DataFrame.abs function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.