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

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

Barbara Streisand
Release: 2024-12-26 04:26:12
Original
113 people have browsed it

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

Filter DataFrame Rows if Value in Column Matches Specific List

The pandas DataFrame rpt has multiple rows of data related to stocks. To retrieve rows where the stock IDs match a specific list of values, the isin method should be employed. Let's explore how to filter DataFrame rows using a list of values:

import pandas as pd

# Create a sample DataFrame
rpt = pd.DataFrame({'STK_ID': ['000002', '600809', '600141', '600329', '603366'],
                   'RPT_Date': ['20120331', '20120331', '20120331', '20120331', '20091231'],
                   'sales': [100, 200, 300, 400, 500]})

# Stock IDs to filter for
stk_list = ['600809', '600141', '600329']

# Filter rows using isin
filtered_rows = rpt[rpt['STK_ID'].isin(stk_list)]
Copy after login

The isin method checks if the values in the specified column are present in the provided list. Rows with matching IDs are filtered into the filtered_rows DataFrame:

print(filtered_rows)

   STK_ID  RPT_Date  sales
0  600809  20120331    200
1  600141  20120331    300
2  600329  20120331    400
Copy after login

This filtering approach avoids the common error of using in, which is not supported for checking if values are in a list. By utilizing isin, the desired rows can be efficiently retrieved from the DataFrame.

The above is the detailed content of How to Filter Pandas DataFrame Rows Based on a List of Values in a Specific Column?. 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