如何替换pandas数据框中的多个值?

时间:2017-07-28 00:44:54

标签: python pandas dataframe

如何使用Pandas DataFrame中的映射替换多个值?

我想用以下映射替换一列。

mapping
apple=fruit
tomato=vegetable
steak=protein
milk=dairy

这样我的专栏就成了。

col1       ->     col1
apple             fruit
apple             fruit
tomato            vegtable
steak             protein
milk              dairy

我怎样才能最有效地完成这项工作?

1 个答案:

答案 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