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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With