Querying a dataframe to return rows based on a list/ndarray of conditions

Say I have a dataframe ‘df’:

enter image description here

And an array of numbers, called ‘profiles’:

[310, 47, 161, 51, 78, 162, 303, 314, 176, 54]

I’m trying to query ‘df’ on column ‘dayNo’ to only returns rows which match the array above (profiles), but not sure how. I attempted the below, but to no avail:

df2 = df.loc[df['dayNo'] == [np.array([profiles], dtype=bool)]]

Any help greatly appreciated, thanks!

>Solution :

You can use boolean indexing with pandas.Series.isin :

df2 = df.loc[df['dayNo'].isin(profiles)]

Another method is pandas.DataFrame.query :

df2 = df.query('dayNo in @profiles')

Leave a Reply