pandas: checking if all given values are in index

578 views Asked by At

I have several pandas data frames with different indexes. Lets say for this example I have indexes from 50 to 200, how can I check if all three given numbers for example [10, 51, 99] are within that index? (I need this for validation purposes to return errors if an index can't be called)

My idea was to use .isin() but with .any() as in the example below it only checks whether any of the values occur in the index. Is there an option to check whether ALL indexes occur? It should return True if all values occur and False as soon as one value doesn't occur.

df.index.isin([10,51,99]).any()
1

There are 1 answers

2
r a f t On

You can use sum().

isin(..) returns a bool array, and sum() basically returns the count of True elements.

So, in your case, you should check if sum() is equal to the length of values you pass in:

df.index.isin([10,51,99]).sum() == 3

If we generalize:

df.index.isin(values).sum() == len(values)

Note: As mentioned by Joooeey in the below comment, this will only work if the index does not contain duplicates.