Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading