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

map output the key value if key not in dict

import pandas as pd

d = {'user': ['bob','alice','bob', 'kk'],
     'item': ['apple','coconut','pear', 'ajay']}
df = pd.DataFrame(data = d)

d = {'apple':1.0,'coconut':0.0}
df['item'] = df['item'].map(d)

Output: df
Out[22]: 
    user  item
0    bob   1.0
1  alice   0.0
2    bob   NaN
3    kk    NaN

Expected output:
Output: df
Out[22]: 
    user  item
0    bob   1.0
1  alice   0.0
2    bob   pear
3    kk    ajay

Above is my piece with the output and expected output. When I am using map. I am getting NaN for key not in map.
My expected output post mapping is below:

Output: df
Out[22]: 
    user  item
0    bob   1.0
1  alice   0.0
2    bob   pear
3    kk    ajay

is it possible to excluded the entry which can’t be mapped?

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

>Solution :

Use Series.fillna by original column:

d = {'apple':1.0,'coconut':0.0}
df['item'] = df['item'].map(d).fillna(df['item'])

print (df)
    user  item
0    bob   1.0
1  alice   0.0
2    bob  pear
3     kk  ajay

Or use Series.replace:

d = {'apple':1.0,'coconut':0.0}
df['item'] = df['item'].replace(d)

print (df)
    user  item
0    bob   1.0
1  alice   0.0
2    bob  pear
3     kk  ajay
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