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

How to Subset Pandas DataFrames Using a List of Values?

Barbara Streisand
Release: 2024-12-21 10:43:10
Original
154 people have browsed it

How to Subset Pandas DataFrames Using a List of Values?

Subsetting Pandas Dataframes Based on a List of Values

In data analysis, it's often necessary to retrieve specific rows from a dataframe based on predefined criteria. Pandas provides various methods for subsetting dataframes, including the ability to select rows based on a list of values.

Utilizing isin() Method

To subset a Pandas dataframe based on a list of values, you can employ the isin() method, as demonstrated below:

import pandas as pd

# Create a Pandas dataframe
df = pd.DataFrame({'A': [5, 6, 3, 4], 'B': [1, 2, 3, 5]})

# Define a list of values to filter by
list_of_values = [3, 6]

# Subset dataframe based on the list
y = df[df['A'].isin(list_of_values)]

print(y)
Copy after login

Output:

   A  B
1  6  2
2  3  3
Copy after login

The isin() method allows you to filter rows where the specified column values match any value in the provided list.

Negating Selection with ~

In certain scenarios, you may need to exclude rows based on the list of values. To achieve this, you can use the ~ operator along with isin(), as illustrated below:

import pandas as pd

# Create a Pandas dataframe
df = pd.DataFrame({'A': [5, 6, 3, 4], 'B': [1, 2, 3, 5]})

# Define a list of values to exclude
list_of_values = [3, 6]

# Subset dataframe excluding the list
z = df[~df['A'].isin(list_of_values)]

print(z)
Copy after login

Output:

   A  B
0  5  1
3  4  5
Copy after login

The ~ operator negates the selection, ensuring that rows with values not in the specified list are displayed.

The above is the detailed content of How to Subset Pandas DataFrames Using 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