Home >Backend Development >Python Tutorial >How to Efficiently Filter Pandas DataFrames Using a List of Values?

How to Efficiently Filter Pandas DataFrames Using a List of Values?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-18 00:32:11622browse

How to Efficiently Filter Pandas DataFrames Using a List of Values?

Filtering Pandas Dataframes with a List of Values

In data manipulation tasks, selecting specific rows from a Pandas dataframe based on a list of values is a common requirement. This article demonstrates how to efficiently achieve this operation.

Using the isin() Method

To select rows where the values of a specified column are present in a given list, the isin() method is a straightforward solution. Let's consider the following Pandas dataframe:

df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})
print(df)

To retrieve rows where column 'A' contains values 3 or 6, we can use:

list_of_values = [3, 6]
result = df[df['A'].isin(list_of_values)]
print(result)

This operation yields the rows with matching 'A' column values:

   A  B
1  6  2
2  3  3

Excluding Values with the ~ Operator

To exclude rows where the 'A' column values are not present in the list, the ~ operator can be employed in conjunction with isin(). For example:

result = df[~df['A'].isin(list_of_values)]
print(result)

This operation excludes rows with 'A' values of 3 or 6:

   A  B
0  5  1
3  4  5

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

Statement:
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