Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does pandas really perform index alignment?

In a long code, I found myself at a point where I had to compare two series. I can’t share the full code but I made example :

series1 = pd.Series(['a', 'b', 'c'], index=[2, 1, 3])
series2 = pd.Series(['b', 'a', 'c'], index=[3, 2, 1])

print(series1)
2    a
1    b
3    c
dtype: object

print(series2)
3    b
2    a
1    c
dtype: object

For the comparison it’s a simple series1 == series2 but surprisingly I got an error :

ValueError: Can only compare identically-labeled Series objects

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

To solve the problem I searched in stackoveflow and people say it’s because of the different indexes which appear to be true because the code below solved my issue :
Pandas "Can only compare identically-labeled DataFrame objects" error

series1.sort_index() == series2.sort_index()

1    False
2     True
3    False
dtype: bool

My question is : do pandas really do index alignment ? Or is it just a myth ? Because I feel like sometimes it does and sometimes not.

Do you guys have an explanation to my error and an answer to my question ?

>Solution :

Prefer the use of eq that is more powerful than == (likewise le/lt/ge/gt in place of <=/</>=/>):

series1.eq(series2)

Output:

1    False
2     True
3    False
dtype: bool

Alternative with a manual reindexing:

series1 == series2.reindex_like(series1)

2     True
1    False
3    False
dtype: bool
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading