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
Release: 2024-12-27 21:27:14
Original
125 people have browsed it

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]})
Copy after login

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

list_of_values = [3, 6]
Copy after login

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)]
Copy after login

Result:

   A  B
1  6  2
2  3  3
Copy after login

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)]
Copy after login

Result:

   A  B
0  5  1
3  4  5
Copy after login

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!

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