pandas dataframe check if index exists in a multi index

user77005 picture user77005 · Jan 22, 2018 · Viewed 11.3k times · Source

I have a pandas Dataframe which has a multiindex created using the columns userid and itemid. df looks like this

                  0     1     2
userid  itemid
007     5000      9     4     3
007     4000      6     7     1
009     3000      1     2     3

I want to check if the index [007, 6000] exists in the dataframe df. How can I do that. If I run the following code there is an error TypeError: unhashable type: 'list'.

if [007, 6000] in df.index:
    print('it works')

Answer

cs95 picture cs95 · Jan 22, 2018

For this -

df

               0  1  2
userid itemid         
7      5000    9  4  3
       4000    6  7  1
9      3000    1  2  3

df.index.values
array([(7, 5000), (7, 4000), (9, 3000)], dtype=object)

You can use df.index.isin.

df.index.isin([(7, 5000)])
array([ True, False, False], dtype=bool)

This gives you a mask corresponding to where that value can be found. If you just want to know whether it exists or not, use np.ndarray.any in conjunction with isin.

df.index.isin([(7, 5000)]).any()
True

df.index.isin([(7, 6000)]).any()
False