W3docs

Use a list of values to select rows from a Pandas dataframe

You can use the .loc property of a Pandas dataframe to select rows based on a list of values.

You can use the .loc accessor in a Pandas DataFrame to select rows. Note that df.loc[list_of_values] filters by index labels, not column values. To filter by column values, combine .loc with .isin():

Selecting rows by column values using .loc and .isin()

list_of_values = [1, 2, 3]
df.loc[df['A'].isin(list_of_values)]

Alternatively, you can use boolean indexing, which is often more idiomatic:

df[df['A'].isin(list_of_values)]

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

You can also chain multiple conditions to select rows:

Chaining multiple conditions to select rows

df.loc[(df['A'].isin(list_of_values)) & (df['B'] == 'some_value')]

You can also use the .query() method to select rows based on a list of values. It is often more readable, but requires the @ prefix for Python variables:

Using .query() to select rows

df.query('A in @list_of_values')

Please note that in the above examples, column A must exist in the DataFrame, otherwise it will raise an error.