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

How to get matching row indices from a pandas query?

Applying a pandas query essentially returns a dataframe that matches the query. I am wondering how one can also retrieve the raw matching row indices (alternatively boolean array)? In particular for dataframes that do have a custom index and therefore do not allow the raw indices to be extracted from the dataframe itself.

    Col1
R1     4
R2     5
R3     6
R4     7

df.query("Col1 > 5") returns

    Col1
R3     6
R4     7

The desired output are however the corresponding row indices = [2,3]

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

Is there any chance to easily retrieve the raw indices with a query without using a secondary compare step?

>Solution :

Call the index after df.query with get_indexer:

[*df.index.get_indexer(df.query("Col1 > 5").index)]

Or:

[*df.index.get_indexer(df.index[df['Col1']>5])]

[2, 3]
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