简体   繁体   English

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

[英]How to replace multiple values in a pandas dataframe?

How can I replace multiple values with a mapping in a Pandas DataFrame? 如何在Pandas DataFrame中使用映射替换多个值?

I have one column that I want to replace with the following mapping. 我有一列要替换为以下映射。

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

So that my column becomes. 这样我的专栏就变成了。

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

How can I do this most efficiently? 我怎样才能最有效地做到这一点?

Just create a dictionary with your mapping and then call Series.map . 只需使用您的映射创建一个字典,然后调用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM