No Alignment When Comparing pandas Series

When you do mathematical operations on two pandas Series (e.g., s1 + s2), the two Series align on their indexes, but when you compare the same two Series (e.g., s1 > s2), the two Series do not align.

Example Code

import pandas as pd
grades1 = pd.Series([1,2,3,4,5], index=['A','B','C','D','F'])
grades2 = pd.Series([1,2,3,4,5], index=['D','C','B','A','F'])

Add the Two Series

grades1 + grades2


A     5
B     5
C     5
D     5
F    10
dtype: int64

Compare the Two Series

grades1 > grades2


A    False
B    False
C    False
D    False
F    False
dtype: bool

I find this confusing, but apparently, it is by design.

There are plenty of ways to get around the problem. Here are a few of them:

Workaround 1: Replace the comparison with an operation and compare the result to a scalar:

grades1 - grades2 > 0

Workaround 2: Sort both Series on index before comparing:

grades1.sort_index() > grades2.sort_index()

Workaround 3: Reindex one Series according to the other:
(I got this solution from here.)

grades1 > grades2.reindex_like(grades1)

All of these will appropriately return the following boolean Series:

A    False
B    False
C     True
D     True
F    False
dtype: bool

Related Training: Advanced Python

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.