Pandas Index Isin Method

Pandas Index Isin Method

I'm having throuble working with the isin method when working with pandas indexes, it always returns False.

from pandas import DataFrame
df = DataFrame(data=[['a', 1], ['b', 2], ['c', 3]], index=['N01', 'N02', 'N03'])
df.index.isin(['01', '02'])

returns

array([False, False, False], dtype=bool)

2 Answers

Use str.contains and pass a regex pattern:

In[5]: df.index.str.contains('01|02')

Out[5]: array([ True,  True, False], dtype=bool)

isin looks for exact matches which is why you get all False array returned

df.index.isin(['01', '02']) method in your example is checking if each of the values in the index is equal to one of the values in the range (similar to SQL).

Therefore in your case the check is: 'N01'=='01' or 'N01' == '02' which is False

The correct usage of .isin() in your case would be:

from pandas import DataFrame
df = DataFrame(data=[['a', 1], ['b', 2], ['c', 3]], index=['N01', 'N02', 'N03'])
df.index.isin(['N01', 'N02'])

which will result in array([True, True, False], dtype=bool)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.