You can use the following basic syntax to filter the rows of a pandas DataFrame that contain a value in a list:
df[df['team'].isin(['A', 'B', 'D'])]
This particular example will filter the DataFrame to only contain rows where the team column is equal to the value A, B, or D.
The following example shows how to use this syntax in practice.
Example: Filter Pandas DataFrame Based on Values in List
Suppose we have the following pandas DataFrame that contains information about various basketball players:
import pandas as pd #create DataFrame df = pd.DataFrame({'team': ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D'], 'points': [18, 22, 19, 14, 14, 11, 20, 28], 'assists': [5, 7, 7, 9, 12, 9, 9, 4], 'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]}) #view DataFrame print(df) team points assists rebounds 0 A 18 5 11 1 A 22 7 8 2 B 19 7 10 3 B 14 9 6 4 C 14 12 6 5 C 11 9 5 6 D 20 9 9 7 D 28 4 12
Now suppose that we would like to filter the DataFrame to only contain rows where the value in the team column is equal to A, B, or D.
We can use the following syntax to do so:
#filter for rows where team is equal to 'A', 'B' or 'D' df[df['team'].isin(['A', 'B', 'D'])] team points assists rebounds 0 A 18 5 11 1 A 22 7 8 2 B 19 7 10 3 B 14 9 6 6 D 20 9 9 7 D 28 4 12
Notice that the filtered DataFrame only contains rows where the value in the team column is equal to A, B, or D.
Also note that you can use the isin() function to filter by numeric values.
For example, we can use the following code to filter for rows where the assists column is equal to 5 or 9:
#filter for rows where assists is equal to 5 or 9 df[df['assists'].isin([5, 9])] team points assists rebounds 0 A 18 5 11 3 B 14 9 6 5 C 11 9 5 6 D 20 9 9
Notice that the filtered DataFrame only contains rows where the value in the assists column is equal to 5 or 9.
Note: You can find the complete documentation for the pandas isin() function here.
Additional Resources
The following tutorials explain how to perform other common tasks in pandas:
Pandas: How to Add Filter to Pivot Table
Pandas: How to Filter for “Not Contains”
Pandas: How to Filter Rows that Contain a Specific String