Pandas DataFrame combine_first() method with examples

Spread the love

The combine_first() method in pandas update null elements with value in the same location in other. Combine two DataFrame objects by filling null values in one DataFrame with non-null values from other DataFrame. The row and column indexes of the resulting DataFrame will be the union of the two.

Syntax –

DataFrame.combine_first(other)

other – Provided DataFrame to use to fill null values.

Examples –

import pandas as pd

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

Now, let’s fill the null values in the first dataframe with non-null values from the second dataframe.

df1.combine_first(df2)

Null values still persist if the location of that null value does not exist in other.

df1 = pd.DataFrame({'A': [None, 0], 'B': [4, None]})
df1
df2 = pd.DataFrame({'B': [3, 3], 'C': [1, 1]}, index=[1, 2])
df2
df1.combine_first(df2)

Rating: 1 out of 5.

Leave a Reply