Home >Backend Development >Python Tutorial >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)]
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
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!