26 Oct Combine two Pandas series into one
To combine two Pandas series into one in Python, use the combine() method. It uses a specific function for the decision, mentioned by the user as a parameter of the combine() method.
We will see an example that will fetch the largest values from both series. Each element of both the series will be compared one by one. Let us see the example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import pandas as pd # Data to be stored in the Pandas Series data1 = [10, 20, 40, 80, 100] data2 = [25, 5, 75, 95, 45] # Create a Series using the Series() method series1 = pd.Series(data1) series2 = pd.Series(data2) # Display the Series print("Before combining the series:\n") print("Series1: \n",series1) print("Series2: \n",series2) def demo(x1, x2) : if (x1 > x2): return x1 else: return x2 # Combine two series into one # The function returns the largest value res = series1.combine(series2, demo) # Display the result print("\nAfter combining into one:\n",res) |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
Before combining the series: Series1: 0 10 1 20 2 40 3 80 4 100 dtype: int64 Series2: 0 25 1 5 2 75 3 95 4 45 dtype: int64 After combining into one: 0 25 1 20 2 75 3 95 4 100 dtype: int64 |
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
No Comments