Pandas Series.combine()


Pandas Series.combine() Tutorial

In this tutorial, we'll explore the Series.combine() method in Pandas, which is used to combine two Series by applying a given function, with well detailed example programs.

The syntax of Series.combine(other, func, fill_value=None, overwrite=True) is:

Series.combine(other, func, fill_value=None, overwrite=True)

where

ParameterDescription
otherThe Series to combine with.
funcThe function to apply to the combined Series.
fill_valueThe value to fill NaN values in either of the Series before combining.
overwriteWhether to overwrite existing non-NaN values in the calling Series. Default is True.
Parameters of Series.combine() function

The Series.combine() method combines two Series, aligning on index, and applies the provided function to each pair of elements. NaN values can be filled with a specified value, and existing non-NaN values can be overwritten.


Examples for Series.combine() function

1. Combine two Series with addition

In this example, we'll use Series.combine() to combine two Series s1 and s2 by applying the addition function. And print the input series, and resulting series to output.

Python Program

import pandas as pd

# Create two Series
s1 = pd.Series({'A': 10, 'B': 20, 'C': 30})
s2 = pd.Series({'A': 5, 'B': 15, 'D': 25})

# Combine using addition function
result = s1.combine(s2, lambda x, y: x + y, fill_value=0)

# Print original Series and combined result
print("Series 1:")
print(s1)
print("\nSeries 2:")
print(s2)
print("\nCombined Result:")
print(result)

Output

Series 1:
A    10
B    20
C    30
dtype: int64

Series 2:
A     5
B    15
D    25
dtype: int64

Combined Result:
A    15
B    35
C    30
D    25
dtype: int64

Summary

In this tutorial, we've covered the Series.combine() method in Pandas, which is useful for combining two Series by applying a given function and handling NaN values.


Python Libraries