Wednesday, December 25, 2024
Google search engine
HomeLanguagesPython | Pandas Index.isin()

Python | Pandas Index.isin()

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.

Pandas Index.isin() function return a boolean array where the index values are in values. compute boolean array of whether each index value is found in the passed set of values. The length of the returned boolean array matches the length of the index.

Syntax: Index.isin(values, level=None)
Parameters : 
values : [set or list-like] Sought values. 
level : Name or position of the index level to use (if the index is a MultiIndex).
Returns : NumPy array of boolean values.
 

Example #1: Use Index.isin() function to check if the index value is present in the passed list of values.

Python3




# importing pandas as pd
import pandas as pd
 
# Creating the Index
idx = pd.Index(['Labrador', 'Beagle', 'Mastiff',
                    'Lhasa', 'Husky', 'Beagle'])
 
# Print the Index
idx


Output : 

Now we find if index labels are present in the passed list. 

Python3




# Passing a list containing two values against
#  which the index labels will be matched
idx.isin(['Lhasa', 'Mastiff'])


Output : 

The function returned an array object having the same size as that of the index. True value means the index label was present in the passed list object and False value means the index label was not present in the passed list object. 
  
Example #2: Use Index.isin() function to check if the labels of MultiIndex are present in the passed list.

Python3




# importing pandas as pd
import pandas as pd
 
# Creating the MultiIndex
midx = pd.MultiIndex.from_arrays([['Mon', 'Tue', 'Wed', 'Thr'],
                 [10, 20, 30, 40]], names =('Days', 'Target'))
 
# Print the MultiIndex
midx


Output : 

Now we will check if the labels in the MultiIndex are present in the passed list or not. 

Python3




# test whether midx labels are in list or not
midx.isin(['Tue', 'Wed', 'Fri', 'Sat'], level ='Days')


Output : 

As we can see in the output, the function has returned an array object having the same size as that of the MultiIndex selected level. True value means the index label was present in the passed list object and False value means the index label was not present in the passed list object.
 

RELATED ARTICLES

Most Popular

Recent Comments