Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas dataframe check if index exists in a multi index

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')
like image 910
user77005 Avatar asked Jan 22 '18 12:01

user77005


People also ask

How do you check if an index exists in pandas DataFrame?

To check if a value exists in the Index of a Pandas DataFrame, use the in keyword on the index property.

How do you check if a value exists in a data frame?

You can check if a column contains/exists a particular value (string/int), list of multiple values in pandas DataFrame by using pd. series() , in operator, pandas. series. isin() , str.


1 Answers

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
like image 170
cs95 Avatar answered Sep 27 '22 17:09

cs95