Ido Yudhatama
Ido Yudhatama

Reputation: 29

How to compare between dictionary value and pandas data frame?

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?

Upvotes: 2

Views: 1277

Answers (3)

adir abargil
adir abargil

Reputation: 5745

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'

Upvotes: 0

Shubham Sharma
Shubham Sharma

Reputation: 71689

You can use boolean indexing with loc:

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

1    Tom
Name: name, dtype: object

Upvotes: 3

Ferris
Ferris

Reputation: 5601

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']

Upvotes: 0

Related Questions