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 I find a row inside pandas DataFrame with row data?

let’s say that I have a pandas DataFrame:

import pandas as pd

df = pd.DataFrame({'id': [0, 2, 1], 'name': ['Sheldon', 'Howards', 'Leonard'], 'points': [10, 5, 20]})

I wanted to search inside this DataFrame a row with the values {'id': 2, 'name': 'Howards', 'points': 5}, How can I search it to receive the index from than, if exists?

And now come my problem. I have a method that receive a dict with unknow keys and a DataFrame with unknow columns too. I need to search inside this DataFrame to discover if have the searched row inside than…

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

I finded this answer that says about a method named iterrows. It’s the better way to find the row? Code:

import pandas as pd

df = pd.DataFrame({'c1': [10, 11, 12], 'c2': [100, 110, 120]})
df = df.reset_index()

search = {'c1': 12, 'c2': 120}
index = -1
for idx, row in df.iterrows():
    if row == search:
        index = idx

If not, what the better way?

>Solution :

With np.logical_and on filter clauses:

df.index[np.logical_and(*[df[k].eq(v) for k, v in search_d.items()])]

Index([1], dtype='int64')
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