+4 votes
in Programming Languages by (60.0k points)

Using the elements of two dataframes, I want to create a new dataframe. Each element in the new dataframe should be the minimum of the corresponding elements of two dataframes.

For example:

df1 and df2 should give df.

df1 =

A  B

5  2

0  4

df2 =

A  B

1  3

1  3

df=

A  B

1  2

0  3

Is there any function for this operation?

1 Answer

+1 vote
by (354k points)
selected by
 
Best answer

You can use the combine() function of pandas. It combines columns of the dataframes element-wise using a given function. Since you want the minimum of the corresponding elements, you can use the minimum() function as an argument to the combine() function.

Here is an example using your values:

>>> import pandas as pd
>>> df1 = pd.DataFrame({'A': [5, 0], 'B': [2, 4]})
>>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
>>> df1
   A  B
0  5  2
1  0  4
>>> df2
   A  B
0  1  3
1  1  3
>>> df1.combine(df2, np.minimum)
   A  B
0  1  2
1  0  3
 


...