pandas Python DataFrame:使用字典替换值,如果不在字典中则转换 NaN

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43367700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:22:45  来源:igfitidea点击:

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

pythonpandasdataframereplace

提问by s900n

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:

我了解如何使用字典替换列值,但是我想将字典中没有的所有值转换为 NaN 或其他值。我得到这个:

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

回答by jezrael

Use map:

使用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