Categories: PandasPython

Using isin() to check membership of a data frame in Python

Click her for course registration !

When a data frame in Python is created via Pandas library, its membership can be checked using function isin(). It is quite similar as with the same function carried out for a Pandas Series, however, now the returned data object is a data frame too.

For example we create a data frame storing information for name and age and city. Then we can check if certain values of the data frame matches the specified values in a list using isin() and filter out those values.

#Import Pandas module
import pandas as pd
#create a dictionary as input for data frame creation
DICT2 = {'age': [32, 31, 19],
            'name': ["shirley","wilson","mico"],
            'city': ["London","Tokyo","Shanghai"]}
#creating data frame
DF2 = pd.DataFrame(DICT2)
DF2
#output
   age     name      city
0   32  shirley    London
1   31   wilson     Tokyo
2   19     mico  Shanghai
#check if values of data frame matches the values in the list
DF2.isin([19, 'London'])
#output
     age   name   city
0  False  False   True
1  False  False  False
2   True  False  False
#we can further filter out values that matches the values in the list
DF2[DF2.isin([19, 'London'])]
#result is a data frame too, with NaN values for other non-matched values
    age name    city
0   NaN  NaN  London
1   NaN  NaN     NaN
2  19.0  NaN     NaN

wilsonzhang746

Recent Posts

Download R Course source files

Click here to download R Course source files !

2 months ago

Download Python Course source files

Click here to download Python Course Source Files !

2 months ago

How to create a data frame from nested dictionary with Pandas in Python

For online Python training registration, click here ! Pandas provides flexible ways of generating data…

5 months ago

How to delete columns of a data frame in Python

For online Python training registration, click here ! Data frame is the tabular data object…

5 months ago

How to assign values to Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago

How to select elements and show information of a Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago