简体   繁体   中英

How to replace multiple values in a pandas dataframe?

How can I replace multiple values with a mapping in a 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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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