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 the most related row from a pandas dataframe by iterating over a dictionary

Let’s assume I have a dataframe like this:

name color shape taste
Apple Red Heart Sweet
Banana Yellow Long Sweet
Cherry Pink Circular Sour
Damson Magenta Circular Sour
Eggplant Violet Long Bitter

And for the input I have a dictionary of one element which be like new_fruit = {'name' : 'Tangerine' , 'color' : 'Orange' , 'shape' : 'Circular', 'taste' : 'Sour'}

What I want is to iterate over this dictionary to get the most identical row(value) from the dataframe. In this case, Circular and Sour which are the Damson and Cherry rows.

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 have tried with code

   for key, value in new_fruit.items():
    if key == 'name':
        continue
    if dataframe[key] == value: # Tried with isin too
        print(dataset[dataset[key] == value])
        break

I know something is wrong, but couldn’t figure it out, can you please help me solve this!

>Solution :

Maybe this will work for you:

mask = df == pd.Series(new_fruit)
items = df.loc[mask.any(axis=1), 'name'].tolist()

Output:

>>> items
['Cherry', 'Damson']
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