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

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

Linda Hamilton
Linda HamiltonOriginal
2024-12-08 20:24:12448browse

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

Filtering DataFrame Rows by Values in a Set List

In Python pandas, you can filter rows based on whether the value in a specific column is present in a given set of values. To achieve this, you can utilize the isin method, as follows:

import pandas as pd

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

# Define the list of stock IDs to filter
stk_list = ['600809', '600141', '600329']

# Filter rows using the `isin` method
filtered_rows = rpt[rpt['STK_ID'].isin(stk_list)]

# Print the filtered DataFrame
print(filtered_rows)

Output:

   STK_ID   STK_Name RPT_Date  sales
0   600809  Company B 20120331     200
1   600141  Company C 20120331     300
2   600329  Company D 20120331     400

The isin method checks if the values in the specified column (in this case, 'STK_ID') are contained in the provided list (stk_list). Rows that meet this condition are retained in the filtered DataFrame.

The above is the detailed content of How to Filter 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