Jeff Saltfist
Jeff Saltfist

Reputation: 943

Pandas - Comparing column values with value in a dictionary

I have a dictionary

d = {1:a,2:a}

I also have a pandas frame "df"

0 x y
1 1 10
2 2 56

for some reason I can not match up x values with dictionary keys:

for index, row in df.iterrows():
    for x,y in d.items():
        if row['x'] == x:
            print "Got a Match"
        else:
            print "No Match Found"

All I got was "No Match Found". Is there something I am doing wrong? The data in the pandas series was "float64" and the keys were "int" in the dictionary, but I converted the pandas series to int, and still was not able to match these items. Any help appreciated.

Thanks

Upvotes: 3

Views: 6728

Answers (2)

roman
roman

Reputation: 117380

If you want to create new column based on the dictionary, you can use pandas.Series.map:

>>> df['n'] = df['x'].map(d)
>>> df
    x   y     n
1   1  10  val1
2  10  56   NaN

Upvotes: 8

piRSquared
piRSquared

Reputation: 294278

consider this df

   x   y
0       
1  1  10
2  2  56
3  3  11

and dictionary

d = {1: 'a', 2: 'a'}

When you use pd.Series.map it fills in where it can and returns NaN where no key exists. This can be useful for identifying where x's are matching and to replace values later.

df.x.map(d)

0
1      a
2      a
3    NaN
Name: x, dtype: object

d_ = {k: 'Match!' for k, _ in d.items()}
df.x.map(d_).fillna('No Match :-(')

0
1          Match!
2          Match!
3    No Match :-(
Name: x, dtype: object

Upvotes: 1

Related Questions