Overview:
- By calling the Series.combine() function, the values from two series instances can be combined to make a new Series.
- The Series.combine() functions takes a function as a parameter. This function should be of the form that takes two values as input and returns one value.
- The NaN/None values can be given default values using the fill-value parameter.
Example – Combine two series instances by selecting minimum value from the two:
# Example Python program to combine two pandas Series instances import pandas as pds
# Create series objects series1 = pds.Series([10, 12, 14, 16, 18]); series2 = pds.Series([11, 13, 15, 17, 19]);
# Combine values from two pandas.series to make a new series combinedSeries = series1.combine(series2, min);
print("Contents of series1:"); print(series1);
print("Contents of series2:"); print(series2);
print("New series obtained by combining two series instances:"); print(combinedSeries); |
Output:
Contents of series1: 0 10 1 12 2 14 3 16 4 18 dtype: int64 Contents of series2: 0 11 1 13 2 15 3 17 4 19 dtype: int64 New series obtained by combining two series instances: 0 10 1 12 2 14 3 16 4 18 dtype: int64 |
Example-Combine two series instances with filling NaN/None with default values:
# Example Python program to combine two pandas Series instances # while replacing NaN/None with default values import pandas as pds
# Create two pandas Series instances series1 = pds.Series([55.1, 55.0, 57, 59]); series2 = pds.Series([53.1, None, 56, 58, -1]);
# Combine values from two series instances by replacing Nan,None with zeros newSeries = series1.combine(series2, max, fill_value=0);
print("Contents of the first Series:"); print(series1);
print("Contents of the second Series:"); print(series2);
print("Contents of the combined Series:"); print(newSeries); |
Output:
Contents of the first Series: 0 55.1 1 55.0 2 57.0 3 59.0 dtype: float64 Contents of the second Series: 0 53.1 1 NaN 2 56.0 3 58.0 4 -1.0 dtype: float64 Contents of the combined Series: 0 55.1 1 55.0 2 57.0 3 59.0 4 0.0 dtype: float64 |