JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Using isin() Function in Pandas DataFrame

Author:JIYIK Last Updated:2025/05/01 Views:

INWe will discuss how to use the like SQL and Not INthe operator to filter pandas in this tutorial DataFrame. In addition, we will also show you how to use isin()the function and 一元运算符(~)filter a single row/column based on a condition, filter multiple columns, filter pandas DataFrame.


Use isin()the function to create a DataFrame from a dictionary object in Pandas

The following example DataFrame contains columns Student Name, Subject, Semester, Marks. Import the pandas library and create a DataFrame.

import pandas as pd

student_record = {
    "Student Name": ["Samreena", "Affan", "Mirha", "Asif"],
    "Subject": ["SDA", "Ethics", "Web Design", "Web Development"],
    "Semester": ["6th", "7th", "5th", "8th"],
    "Marks": [100, 90, 80, 70],
}
index_labels = [0, 1, 2, 3]
df = pd.DataFrame(student_record, index=index_labels)
print(df)

Output:

   Student Name         Subject  Semester  Marks
0     Samreena              SDA      6th    100
1        Affan           Ethics      7th     90
2        Mirha       Web Design      5th     80
3         Asif  Web Development      8th     70

isin()Filtering a Pandas DataFrame using a function

We can filter pandas rows using a method similar to INthe operator in SQL .isin()DataFrame

To filter the rows, a single column is checked for the desired element. Using pd.series.isin()the function, we can check if the search element is present in the series.

If the element would match in the series, return it true, otherwise return it false.

For example, we want to Subjectreturn rows that contain the subjects Web Designand in the column Web Development.

import pandas as pd

student_record = {
    "Name": ["Samreena", "Affan", "Mirha", "Asif"],
    "Subject": ["SDA", "Ethics", "Web Design", "Web Development"],
    "Semester": ["6th", "7th", "5th", "8th"],
    "Marks": [100, 90, 80, 70],
}
index_labels = [0, 1, 2, 3]
dataframe = pd.DataFrame(student_record, index=index_labels)
# Find elements in a Column to return rows
subjects_list = ["Web Design", "Web Development"]
dataframe1 = dataframe[dataframe.Subject.isin(subjects_list)]
print(dataframe1)

Output:

    Name          Subject   Semester  Marks
2   Mirha       Web Design      5th     80
3   Asif   Web Development      8th     70

Note that only those StudentName Web Developmentand Web DesignSubject are returned.

We can return a boolean array by displaying trueand using the Pandas DataFrame row indexing .false

import pandas as pd

student_record = {
    "Name": ["Samreena", "Affan", "Mirha", "Asif"],
    "Subject": ["SDA", "Ethics", "Web Design", "Web Development"],
    "Semester": ["6th", "7th", "5th", "8th"],
    "Marks": [100, 90, 80, 70],
}
index_labels = [0, 1, 2, 3]

dataframe = pd.DataFrame(student_record, index=index_labels)
subjects_list = ["Web Design", "Web Development"]
dataframe1 = dataframe.Subject.isin(subjects_list)
print(dataframe1)

Output:

0    False
1    False
2    True
3    True
Name: Subject, dtype: bool

isin()Filter multiple columns in a Pandas DataFrame using the

We can also isin()apply filters on multiple columns using the method. For example, we want to retrieve all SDArows that have subject or fifth semester.

import pandas as pd

student_record = {
    "Name": ["Samreena", "Affan", "Mirha", "Asif"],
    "Subject": ["SDA", "Ethics", "Web Design", "Web Development"],
    "Semester": ["6th", "7th", "5th", "8th"],
    "Marks": [100, 90, 80, 70],
}
index_labels = [0, 1, 2, 3]
dataframe = pd.DataFrame(student_record, index=index_labels)
dataframe1 = dataframe[
    dataframe[["Subject", "Semester"]].isin(["SDA", "7th"]).any(axis=1)
]
print(dataframe1)

Output:

       Name  Subject  Semester  Marks
0   Samreena    SDA      6th    100
1     Affan  Ethics      7th     90

Filtering a Pandas DataFrame using the method with Not (~)a matching conditionisin()

isin()INThe behavior of the method is similar to the operator in SQL . We will use 一元运算符 (~)to implement Not INthe operator.

For example, we want to display only those rows that do not contain the subject Web Designand .Ethics

import pandas as pd

student_record = {
    "Name": ["Samreena", "Affan", "Mirha", "Asif"],
    "Subject": ["SDA", "Ethics", "Web Design", "Web Development"],
    "Semester": ["6th", "7th", "5th", "8th"],
    "Marks": [100, 90, 80, 70],
}
index_labels = [0, 1, 2, 3]
dataframe = pd.DataFrame(student_record, index=index_labels)
subjects_list = ["Web Design", "Ethics"]

# Applying Not operator
dataframe1 = dataframe[~dataframe.Subject.isin(subjects_list)]
print(dataframe1)

Output:

       Name          Subject  Semester  Marks
0  Samreena              SDA      6th    100
3      Asif  Web Development      8th     70

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Convert Pandas to CSV without index

Publish Date:2025/05/01 Views:159 Category:Python

As you know, an index can be thought of as a reference point used to store and access records in a DataFrame. They are unique for each row and usually range from 0 to the last row of the DataFrame, but we can also have serial numbers, dates

Convert Pandas DataFrame to Dictionary

Publish Date:2025/05/01 Views:197 Category:Python

This tutorial will show you how to convert a Pandas DataFrame into a dictionary with the index column elements as keys and the corresponding elements of other columns as values. We will use the following DataFrame in the article. import pan

Convert Pandas DataFrame columns to lists

Publish Date:2025/05/01 Views:191 Category:Python

When working with Pandas DataFrames in Python, you often need to convert the columns of the DataFrame into Python lists. This process is very important for various data manipulation and analysis tasks. Fortunately, Pandas provides several m

Subtracting Two Columns in Pandas DataFrame

Publish Date:2025/05/01 Views:120 Category:Python

Pandas can handle very large data sets and has a variety of functions and operations that can be applied to the data. One of the simple operations is to subtract two columns and store the result in a new column, which we will discuss in thi

Dropping columns by index in Pandas DataFrame

Publish Date:2025/05/01 Views:99 Category:Python

DataFrames can be very large and can contain hundreds of rows and columns. It is necessary to master the basic maintenance operations of DataFrames, such as deleting multiple columns. We can use dataframe.drop() the method to delete columns

Pandas Copy DataFrame

Publish Date:2025/05/01 Views:53 Category:Python

This tutorial will show you how to DataFrame.copy() copy a DataFrame object using the copy method. import pandas as pd items_df = pd . DataFrame( { "Id" : [ 302 , 504 , 708 ], "Cost" : [ "300" , "400" , "350" ], } ) print (items_df) Output:

Pandas DataFrame.ix[] Function

Publish Date:2025/05/01 Views:168 Category:Python

Python Pandas DataFrame.ix[] function slices rows or columns based on the value of the argument. pandas.DataFrame.ix[] grammar DataFrame . ix[index = None , label = None ] parameter index Integer or list of integers used to slice row indice

Pandas DataFrame.describe() Function

Publish Date:2025/05/01 Views:120 Category:Python

Python Pandas DataFrame.describe() function returns the statistics of a DataFrame. pandas.DataFrame.describe() grammar DataFrame . describe( percentiles = None , include = None , exclude = None , datetime_is_numeric = False ) parameter perc

Pandas DataFrame.astype() Function

Publish Date:2025/05/01 Views:160 Category:Python

Python Pandas DataFrame.astype() function changes the data type of an object to the specified data type. pandas.DataFrame.astype() grammar DataFrame . astype(dtype, copy = True , errors = "raise" ) parameter dtype The data type we want to a

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial