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?
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