
The combine method perform column-wise combine with another DataFrame. Combines a DataFrame with other DataFrame using func to element-wise combine columns. The row and column indexes of the resulting DataFrame will be the union of the two.
Syntax –
DataFrame.combine(other, func, fill_value=None, overwrite=True)
other – The DataFrame to merge column-wise.
func – Function that takes two series as inputs and return a Series or a scalar. Used to merge the two dataframes column by columns.
fill_value – The value to fill NaNs with prior to passing any column to the merge func.
overwrite – If True, columns in self that do not exist in other will be overwritten with NaNs.
Examples –
Let’s create two dataframes.
import pandas as pd
import numpy as np
df1 = pd.DataFrame({'A': [0, 0], 'B': [4, 4]})
df1

df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
df2

Now, Let’s create a function that chooses the smaller column.
def take_smaller(s1, s2):
if s1.sum() < s2.sum():
return s1
else:
return s2
Now apply this function to merge two dataframes column by column.
df1.combine(df2, take_smaller)

Example using a true element-wise combine function.
df1 = pd.DataFrame({'A': [5, 0], 'B': [2, 4]})
df1

df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
df2

df1.combine(df2, np.minimum)
