How to compare between dictionary value and pandas data frame?

Viewed 469

So, I have dataframe like this, imported from csv file

name math physic
James 80 90
Tom 60 70
Jerry 90 60

and I have a dictionary

data = {'math': 60, 'physic': 70}

I want to check for every value of data dict and compare it with data frame. If the matching value of math and physic it should return the name. In this case Tom.

How can I do this? Any suggestion?

3 Answers

You can use boolean indexing with loc:

df.loc[df[data].eq(data.values()).all(1), 'name']

1    Tom
Name: name, dtype: object

Usually find operation is not so efficient in pandas and numpy but that would do:

df[(df['math'] == mydict['math'] )& (df['physic'] == mydict['physic'] )]['name'][0]
'Tom'

return the intersection of data and DataFrame:

df_str = '''
name    math    physic
James   80  90
Tom 60  70
Jerry   90  60
'''
df = pd.read_csv(io.StringIO(df_str.strip()), sep='\s+', index_col=False)

data = {'math': 60, 'physic': 70}
def query_name(data):
    df2 = pd.Series(data).to_frame().T
    dfn = pd.merge(df, df2, on=['math', 'physic'], how='inner')
    return dfn

data = {'math': 90, 'physic': 60}
query_name(data)
['Jerry']
Related