How to combine a pandas Series with Scalar using Series.combine() method?

PandasServer Side ProgrammingProgramming

The combine() method in pandas series combines two series objects or combines a series with a scalar according to the specified function. The combine() method takes two required positional arguments. The first argument is another series object or a scalar, and the second argument is a function.

The combine() method takes elements from series objects and a value from its parameter based on the specified function it will combine both series and scalar and returns a series object.

Example 1

import pandas as pd

# create pandas Series
series = pd.Series({'i':92,'j':70,"k":88})

print("Series object:",series)

# combine series with scalar
print("combined series:",series.combine(75,max))

Explanation

In this example, we will combine the Series with the scalar value with the 'max' function. The 'max' method takes two elements one from the Series and another one is the scalar value then compares two and returns a single element which one is maximum.

Output

Series object:
i 92
j 70
k 88
dtype: int64

combined series:
i 92
j 75
k 88
dtype: int64

In the above block, we can see the resultant series object which is created by combine() method.

Example 2

import pandas as pd

# create pandas Series
series = pd.Series([50,40,70,30,60,20])

print("Series object:",series)

# combine series with scalar
print("combined series:",series.combine(50,min))

Explanation

Initially, we have created a pandas Series with a python list of integer values. And applied the combine() method with a scalar value “50” and a “min” function.

Output

Series object:
0 50
1 40
2 70
3 30
4 60
5 20
dtype: int64

combined series:
0 50
1 40
2 50
3 30
4 50
5 20
dtype: int64

The Series.combine() method returns a series in which the elements are having a smaller value compared to scalar one otherwise elements are replaced by that scalar value.

For this example, the scalar value “50” is replaced at “0,2,3,4” index positions.

raja
Updated on 09-Mar-2022 07:36:37

Advertisements