Python | Pandas Series.combine()

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages.

Pandas

is one of those packages and makes importing and analyzing data much easier. Pandas

Series.combine()

is a series mathematical operation method. This is used to combine two series into one. The shape of output series is same as the caller series. The elements are decided by a function passed as parameter to

combine()

method. The shape of both series has to be same otherwise it will throw an error.

Syntax: Series.combine(other, func, fill_value=nan) Parameters: other: other series or list type to be combined with caller series func: Function passed as parameter which will decide from which series the element should be put at that index fill_value: integer value of level in case of multi index Return: Combined series with same shape as caller series

Example #1:

In this example, two lists are made and converted into pandas series using .Series() method. A function is made using lambda which checks which values is smaller in both series and returns whichever is the smaller.

Python3
# importing pandas module
import pandas as pd

# creating first series
first =[1, 2, 5, 6, 3, 7, 11, 0, 4]

# creating second series
second =[5, 3, 2, 1, 3, 9, 21, 3, 1]

# making series
first = pd.Series(first)

# making seriesa
second = pd.Series(second)

# calling .combine() method
result = first.combine(second, (lambda x1, x2: x1 if x1 < x2 else x2))

# display
result