How does pandas series combine_first() method work?

PandasServer Side ProgrammingProgramming

The combine_first() method in the pandas series is used to combine two series objects. And it works similar to the series.combine() method here the difference is it updates the null elements with elements in the same location of another series (second series object). And the combine_first() method takes only a parameter which is nothing but a second series object.

The combine_first() method takes two series objects and updates the null elements by filling non-null values in another series object.

Example 1

import pandas as pd
import numpy as np

# create pandas Series1
series1 = pd.Series([2, 4, np.nan, 7])

print("First series object:",series1)

# create pandas Series2
series2 = pd.Series([9,4,5,6])

print("Second series object:",series2)

# combine
print("combined series:",series1.combine_first(series2))

Explanation

In this example, we have created two pandas series objects “series1” and “series2”, the series1 is created with one Nan value. And we applied the combine_first() method on these two series objects.

Output

First series object:
0 2.0
1 4.0
2 NaN
3 7.0
dtype: float64

Second series object:
0 9
1 4
2 5
3 6
dtype: int64

combined series:
0 2.0
1 4.0
2 5.0
3 7.0
dtype: float64

In the above output block, we can see the resultant series object which is created by the combine_first() method. Here the NaN value at index position “2” is updated with an element from the same location of the second series object. And remaining values are updated by first series elements only.

Example 2

import pandas as pd
import numpy as np

# create pandas Series1
series1 = pd.Series([3,6,8,7])

print("First series object:",series1)

# create pandas Series2
series2 = pd.Series([9,4,5,np.nan])

print("Second series object:",series2)

# combine
print("combined series:",series1.combine_first(series2))

Explanation

In this example, the second series object has a nan value which can be updated with elements of the first series object at the same location.

Output

First series object:
0 3
1 6
2 8
3 7
dtype: int64

Second series object:
0 9.0
1 4.0
2 5.0
3 NaN
dtype: float64

combined series:
0 3
1 6
2 8
3 7
dtype: int64

The Series.combine_first() method returns a series with updated null values. The row indexes of the resulting series object will be the union of the two input series objects.

raja
Updated on 09-Mar-2022 07:38:48

Advertisements