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. The syntax for using .loc
is as follows:
df.loc[list_of_values]
For example, if you have a dataframe df
with a column 'A' and you want to select all rows where the value in column 'A' is in the list [1, 2, 3]
, you would use the following code:
list_of_values = [1, 2, 3]
df.loc[df['A'].isin(list_of_values)]
Watch a video course
Python - The Practical Guide
You can also chain 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's a little more flexible and readable than loc
df.query('A in @list_of_values')
Please note that in the above examples, the column A must exist in the Dataframe, otherwise it will raise an error.