How to Use 'NOT IN' Filter in Pandas?

In this tutorial, we will learn how can you use the NOT IN filter in Pandas DataFrame with the help of Python program? By Pranit Sharma Last updated : April 18, 2023

What is 'NOT IN' Filter in Pandas?

The "NOT IN" the filter is used to check whether a particular data is available in the DataFrame or not. The "NOT IN" the condition in pandas is checked by using the DataFrame.isin() operator.

How to Use 'NOT IN' Filter?

To use the "NOT IN" filter in Pandas, you can use the DataFrame.isin() method, which checks whether each element of a DataFrame is contained in the given values.

Syntax

The following is the syntax to use NOT IN filter using the isin() method:

DataFrame[~DataFrame[column_name].isin(list)]

It takes DataFrame as a parameter. Secondly, it takes the column name and the list of elements that needs to be excluded.

Let us understand with the help of an example.

Python Program to Use 'NOT IN' Filter in Pandas

# Importing pandas package
import pandas as pd

# Creating a dictionary of student marks
d = {
    "Peter":[65,70,70,75],
    "Harry":[45,56,66,66],
    "Tom":[67,87,65,53],
    "John":[56,78,65,64]
}

# Now, Create DataFrame and assign index name 
# as subject names
df = pd.DataFrame(d,index=["Maths","Physics","Chemistry","English"])

# Printing the DataFrame
print(df,"\n")

# For filtering data we need to assign a list of 
# elements which we want to exclude
# Creating a list of single element where element = 70 
# which mean we need to exclude those rows where marks 
# are 70 and column value is peter
list = [70]

# Applying Filter in Peter column
print(df[~df['Peter'].isin(list)])

Output

           Peter  Harry  Tom  John
Maths         65     45   67    56
Physics       70     56   87    78
Chemistry     70     66   65    65
English       75     66   53    64 

         Peter  Harry  Tom  John
Maths       65     45   67    56
English     75     66   53    64

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.