Python DataFrame : Replace values using dictionary, 如果不在字典中则转换 NaN

标签 python pandas dataframe replace

我了解如何使用字典替换列值,但是我想将所有不在我的字典中的值转换为 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

最佳答案

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

关于Python DataFrame : Replace values using dictionary, 如果不在字典中则转换 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43367700/

相关文章:

python - 使用 pandas read_gbq 将日期字符串传递到函数中无法识别

Python - 为什么我可以用实例调用类方法?

Python Pandas,删除 NaN

python - 将元组应用于数据帧不会保留类型

R Apply() 函数应用于特定数据帧列

python - 在数据框中成对排列条目序列

Python 和代理 - urllib2.URLError : <urlopen error [Errno 110] Connection timed out>

python - Django 头像类不起作用

python - pandas 排序值以获得 groupby 中每一列的前 5 名

python - 如何使用 Pandas 从 DataFrame 中拆分列