如何使用Pandas DataFrame中的映射替换多个值?
我想用以下映射替换一列。
mapping
apple=fruit
tomato=vegetable
steak=protein
milk=dairy
这样我的专栏就成了。
col1 -> col1
apple fruit
apple fruit
tomato vegtable
steak protein
milk dairy
我怎样才能最有效地完成这项工作?
答案 0 :(得分:2)
只需使用您的映射创建一个字典,然后调用Series.map
。
>>> d = {'apple': 'fruit',
'tomato': 'vegetable',
'steak': 'protein',
'milk': 'dairy'}
>>> df.col1.map(d)
0 fruit
1 fruit
2 vegetable
3 protein
4 dairy
Name: col1, dtype: object