Pandas isin index method

I work 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)
+4
source share
2 answers

Use str.containsand pass the regex pattern:

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

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

isinlooking for exact matches, so you get the whole array Falsereturned

+4
source

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

Therefore, in your case, a check: 'N01'=='01' or 'N01' == '02' whichFalse

Proper use .isin()in your case will be:

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

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

0

Source: https://habr.com/ru/post/1678542/


All Articles