8

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

1 Answer 1

19

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
Sign up to request clarification or add additional context in comments.

2 Comments

what is the difference between map and replace?
@IndrajeetGour - difference is with missing values. If use map and some category is missing, get NaNs. If use replace, catagory is untouched like in question last 2 rows..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.