Filtering DataFrames by Column Values in a List
When working with pandas DataFrames, it is important to be able to filter the rows based on specific criteria. One of the common scenarios is to select rows where a column value is present in a provided list.
For example, consider the DataFrame rpt with the columns STK_ID, STK_Name, RPT_Date, and sales. We can easily filter the rows for a specific stock ID using the == operator:
rpt[rpt['STK_ID'] == '600809']
However, what if we want to filter rows where the STK_ID column contains values from a list, such as ['600809','600141','600329']? Using the == operator with a list does not work in pandas.
To achieve this, we can use the isin method:
stk_list = ['600809','600141','600329'] rpt[rpt['STK_ID'].isin(stk_list)]
The isin method checks if the column values are present in the provided list and returns a boolean mask. The resulting DataFrame will contain only the rows where the STK_ID value matches at least one of the values in the list.
This method is particularly useful when dealing with large DataFrames or when the list of values to filter by is dynamic or changes frequently.
The above is the detailed content of How to Filter Pandas DataFrame Rows Based on a List of Column Values?. For more information, please follow other related articles on the PHP Chinese website!