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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-12-27 21:27:14121browse

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

Selecting Rows from a DataFrame Based on a List of Values in Pandas

This question addresses the challenge of subsetting rows from a Pandas dataframe based on a list of values.

Question:

Given the dataframe:

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

How can we select rows where the 'A' column values match elements in a list, such as:

list_of_values = [3, 6]

Answer:

To filter the dataframe based on a list of values, we can utilize the isin method:

y = df[df['A'].isin(list_of_values)]

Result:

   A  B
1  6  2
2  3  3

To exclude rows with values not present in the list, we can use the logical not operator (~) with isin:

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

Result:

   A  B
0  5  1
3  4  5

The above is the detailed content of How to Select Pandas DataFrame Rows Based on 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