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

Question:

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!

Asked By: K.Best

||

Answers:

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')
Answered By: abokey
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.