Python | Pandas Series.combine_first ()

combine_first() Pandas combine_first() is used to combine two episodes into one. The result is the union of the two rows, that is, in the case of a Null value in the caller row, the value from the passed row is taken. In case both NULL values ​​have the same index, NULL is returned at that index.

Note. This method is different from Series.combine (), which takes a function as a parameter to determine the output value.

Syntax : Series.combine_first(other)

Parameters:
other: Other series to be combined with caller series.

Return type: Pandas series

Example:
This example creates two series from a list using the Pandas Series () method. Some Null values ​​are also passed to each list using Numpy np.nan . Then both series are combined using .combine_first () . First, the method is called series1, and the result is stored in result1, and then series2 is called similarly and stored in result2 . Both returned series are then printed to compare the results.

# pandas module import

import pandas as pd 

 
# numpy module import

import numpy as np 

 
# create episode 1

series1 = pd.Series ([ 70 , 5 , 0 , 225 , 1 , 16 , np.nan, 10 , np.nan]) 

 
# creating episode 2

series2 = pd.Series ([ 27 , np.nan, 2 , 23 , 1 , 95 , 53 , 10 , 5 ]) 

 
# merge and return results to a variable
# call to series1 < / p>

result1 = series1.combine_first (series2)

 
# call to series2

result2 = series2.combine_first (series1)

 
# print result

print ( 'Result 1:' , result1, ' Result 2: ' , result2)

Output:
As shown in the output, although the same series have been combined, the output is different. This is because the combine_first () method combine_first () sets the priority of the first series (Caller series) earlier. If there is a zero at this position, it gets the value with the same index from the second series.

 Result 1: 0 70.0 1 5.0 2 0.0 3 225.0 4 1.0 5 16.0 6 53.0 7 10.0 8 5.0 dtype: float64 Result 2: 0 27.0 1 5.0 2 2.0 3 23.0 4 1.0 5 95.0 6 53.0 7 10.0 8 5.0 dtype: float64 




Get Solution for free from DataCamp guru