Methods for Combining and Comparing Series
Sometimes we have more than one Series and want to combine or compare them.
Suppose we have:
marks = pd.Series([80, 90, 70, 85])
grace_marks = pd.Series([5, 0, 10, 5])
combine(): The combine() method combines two Series by applying a function to corresponding values.
For example:
marks.combine(grace_marks, max)
output:
0 80
1 90
2 70
3 85
dtype: int64
Here, Pandas compares the corresponding values from both Series and applies the max function.
For example:
max(80, 5) → 80
max(90, 0) → 90
max(70, 10) → 70
max(85, 5) → 85
combine_first(): The combine_first() method uses values from another Series to fill missing values in the first Series.
For example:
marks = pd.Series([80, None, 70])
other_marks = pd.Series([85, 90, 75])
marks.combine_first(other_marks)
output:
0 80.0
1 90.0
2 70.0
dtype: float64
Here, the missing value at index 1 is filled using the value from other_marks at the same index.
compare(): The compare() method compares two Series and shows the values that are different.
For example:
marks = pd.Series([80, 90, 70])
other_marks = pd.Series([80, 95, 70])
marks.compare(other_marks)
output:
self other
1 90.0 95.0
Here, only the value at index 1 is different, so Pandas shows that difference.
This is useful when we want to compare two versions of the same data.
equals(): The equals() method checks whether two Series contain the same values and have the same index.
For example:
marks = pd.Series([80, 90, 70])
other_marks = pd.Series([80, 90, 70])
marks.equals(other_marks)
output:
True
If the values or indexes are different, it returns False.