Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Pandas isin()
In this tutorial, you will learn about the isin() method in Pandas with the help of examples.
The isin() method in Pandas is used to filter data, checking whether each element in a DataFrame or Series is contained in values from another Series, list, or DataFrame.
Example
import pandas as pd
# create a sample DataFrame
data = {'A': [1, 2, 3, 4],
'B': [5, 6, 7, 8]}
df = pd.DataFrame(data)
# select rows where DataFrame column 'A' is in the values list
result = df['A'].isin([2, 4])
# print the resulting boolean DataFrame
print(result)
'''
Output
0 False
1 True
2 False
3 True
Name: A, dtype: bool
'''
isin() Syntax
The syntax of the isin() method in Pandas is:
obj.isin(values)
isin() Argument
The isin() method takes the following argument:
values- a set of values which can be a list, Series, or DataFrame.
isin() Return Value
The isin() method returns a boolean DataFrame (or Series) showing whether each element in the object is contained in the specified values.
Example 1: Using isin() with a Series
import pandas as pd
# create a sample Series
series_data = pd.Series([1, 2, 3, 4, 5])
# checking elements in Series that are in the provided list
result = series_data.isin([1, 3, 5])
# print the resulting boolean Series
print(result)
Output
0 True 1 False 2 True 3 False 4 True dtype: bool
In this example, the isin() method checks each value in the Series against the provided list, resulting in a boolean Series.
Example 2: DataFrame with Multiple Columns
import pandas as pd
# create a sample DataFrame
data = {'A': [1, 2, 3],
'B': [4, 5, 6]}
df = pd.DataFrame(data)
# specify values to check in each column
values = {'A': [1, 3], 'B': [5, 6]}
# check if DataFrame elements are present in the specified values
result = df.isin(values)
print(result)
Output
A B
0 True False
1 False True
2 True True
Here, we provided a dictionary to the isin() method, containing values to check for each column in the DataFrame.
Example 3: Entire DataFrame Comparison
import pandas as pd
# create two sample DataFrames
data = {'A': [1, 2, 3],
'B': [4, 5, 6]}
df1 = pd.DataFrame(data)
data2 = {'A': [1, 2],
'B': [4, 5]}
df2 = pd.DataFrame(data2)
# check whether df1 contains elements of df2
result = df1.isin(df2)
print(result)
Output
A B
0 True True
1 True True
2 False False
In this case, we used isin() to check if elements of one DataFrame (df1) are present in another DataFrame (df2).