Home >Backend Development >Python Tutorial >How Can I Filter Pandas DataFrame Rows Based on a List of Values?
Filtering Dataframe Rows Based on Values in a List
In the context of Python dataframes, filtering rows based on specific values can be achieved using the pandas library. This question addresses the requirement to filter rows where the value in a particular column matches any of the elements in a provided list.
To accomplish this, the isin() method should be employed, as opposed to the attempted in operator which is not recognized by pandas. The rpt['STK_ID'].isin(stk_list) expression checks whether the values in the STK_ID column are present in the stk_list variable, effectively selecting the rows that meet this condition.
For example, consider a dataframe rpt:
rpt <class 'pandas.core.frame.DataFrame'> MultiIndex: 47518 entries, ('000002', '20120331') to ('603366', '20091231') Data columns: STK_ID 47518 non-null values STK_Name 47518 non-null values RPT_Date 47518 non-null values sales 47518 non-null values
To filter rows where the STK_ID value is either '600809', '600141', or '600329':
stk_list = ['600809', '600141', '600329'] rst = rpt[rpt['STK_ID'].isin(stk_list)]
The rst dataframe will now contain only the rows corresponding to the specified stock IDs from the stk_list.
The above is the detailed content of How Can I Filter Pandas DataFrame Rows Based on a List of Values?. For more information, please follow other related articles on the PHP Chinese website!