Home >Backend Development >Python Tutorial >How to Efficiently Filter Pandas DataFrames Using a List of Values?
In data manipulation tasks, selecting specific rows from a Pandas dataframe based on a list of values is a common requirement. This article demonstrates how to efficiently achieve this operation.
To select rows where the values of a specified column are present in a given list, the isin() method is a straightforward solution. Let's consider the following Pandas dataframe:
df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]}) print(df)
To retrieve rows where column 'A' contains values 3 or 6, we can use:
list_of_values = [3, 6] result = df[df['A'].isin(list_of_values)] print(result)
This operation yields the rows with matching 'A' column values:
A B 1 6 2 2 3 3
To exclude rows where the 'A' column values are not present in the list, the ~ operator can be employed in conjunction with isin(). For example:
result = df[~df['A'].isin(list_of_values)] print(result)
This operation excludes rows with 'A' values of 3 or 6:
A B 0 5 1 3 4 5
The above is the detailed content of How to Efficiently Filter Pandas DataFrames Using a List of Values?. For more information, please follow other related articles on the PHP Chinese website!