Home > Backend Development > Python Tutorial > How to Filter Pandas DataFrame Rows Based on a List of Column Values?

How to Filter Pandas DataFrame Rows Based on a List of Column Values?

Patricia Arquette
Release: 2024-12-17 12:10:25
Original
211 people have browsed it

How to Filter Pandas DataFrame Rows Based on a List of Column Values?

Filtering DataFrames by Column Values in a List

When working with pandas DataFrames, it is important to be able to filter the rows based on specific criteria. One of the common scenarios is to select rows where a column value is present in a provided list.

For example, consider the DataFrame rpt with the columns STK_ID, STK_Name, RPT_Date, and sales. We can easily filter the rows for a specific stock ID using the == operator:

rpt[rpt['STK_ID'] == '600809']
Copy after login

However, what if we want to filter rows where the STK_ID column contains values from a list, such as ['600809','600141','600329']? Using the == operator with a list does not work in pandas.

To achieve this, we can use the isin method:

stk_list = ['600809','600141','600329']
rpt[rpt['STK_ID'].isin(stk_list)]
Copy after login

The isin method checks if the column values are present in the provided list and returns a boolean mask. The resulting DataFrame will contain only the rows where the STK_ID value matches at least one of the values in the list.

This method is particularly useful when dealing with large DataFrames or when the list of values to filter by is dynamic or changes frequently.

The above is the detailed content of How to Filter Pandas DataFrame Rows Based on a List of Column Values?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template