Dihre
Dihre

Reputation: 53

Element wise max comparison of two pandas dataframes

I have two dataframes df1 and df2.

df1 = 

    A1 B1 C1
0   1  2  0
1   4  2  1
2   2  1  5


df2 =

    A2 B2 C2
0   2  1  5
1   1  3  2
2   2  2  4
 

And I wish to create a third dataframe which has the max values between the corresponding elements of the two dataframes.

I.e.

df3 = max(df1, df2)

print(df3)

    A3 B3 C3
0   2  2  5
1   4  3  2
2   2  2  5

How do I achieve this?

Thanks!

Upvotes: 2

Views: 1847

Answers (2)

Erfan
Erfan

Reputation: 42916

We can use DataFrame.max over the index:

df2.columns = df1.columns
df3 = pd.concat([df1, df2]).max(level=0)
df3.columns = df3.columns.str.replace("\d", "3", regex=True)
   A3  B3  C3
0   2   2   5
1   4   3   2
2   2   2   5

Upvotes: 3

Anurag Dabas
Anurag Dabas

Reputation: 24314

try via where() method and rename() method:

out=df1.where(df1.values>df2.values,df2.values).rename(columns=lambda x:x[0]+'3')

OR

via numpy's where() and DataFrame() method:

out=pd.DataFrame(np.where(df1.values>df2.values,df1.values,df2.values),columns=['A3','B3','C3'])

output of out:

    A3  B3  C3
0   2   2   5
1   4   3   2
2   2   2   5

Upvotes: 1

Related Questions