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

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

Barbara Streisand
Release: 2024-12-04 02:25:12
Original
893 people have browsed it

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
Copy after login

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)]
Copy after login

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!

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