Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python DataFrame: Replace values using dictionary, convert NaN if not in dictionary

I understand how to replace column values with using a dictionary however I want to convert all of the values that are not in my dictionary to NaN or some other value. I am getting this:

Dictionary is:
{'apple': 1, 'peach': 6, 'watermelon': 4, 'grapes': 5, 'orange': 2, 
'banana': 3}

DataFrame is: 
fruit_tag
apple
orange
banana
watermelon
red
blue

I use: 
df["fruit_tag"].replace(dict, inplace=True)
print(df)

I get:
fruit_tag
1
2
3
4
red
blue

What I want to get:
fruit_tag
1
2
3
4
NaN
NaN
like image 760
s900n Avatar asked Apr 12 '17 11:04

s900n


1 Answers

Use map:

d = {'apple': 1, 'peach': 6, 'watermelon': 4, 'grapes': 5, 'orange': 2,'banana': 3}

df["fruit_tag"] = df["fruit_tag"].map(d)
print (df)
   fruit_tag
0        1.0
1        2.0
2        3.0
3        4.0
4        NaN
5        NaN
like image 157
jezrael Avatar answered Sep 19 '22 00:09

jezrael