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')
To check if a value exists in the Index of a Pandas DataFrame, use the in keyword on the index property.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With