如何在Pandas中依据指定列内容自动填充新列行数据?
Absolutely, there are clean and efficient ways to automate this in pandas! The most straightforward approach uses a dictionary mapping combined with the map() function—it’s readable, fast, and perfect for this kind of categorical assignment.
Step 1: Define your classification mapping
First, create a dictionary that links each food name to its corresponding category:
classificacao_map = { "iogurte": "laticinio", "sardinha": "peixe", "manteiga": "gordura animal", "maçã": "fruta", "milho": "cereal" }
Step 2: Apply the mapping to create the new column
Use the map() method on the "alimento" column to generate the "classificacao" column in your DataFrame:
import pandas as pd # Load your dataset alimentos = pd.read_csv("alimentos.csv", sep=',', encoding='utf-8') alimentos.reset_index(drop=True, inplace=True) # Avoids duplicate index columns # Add the classification column alimentos['classificacao'] = alimentos['alimento'].map(classificacao_map)
Resulting DataFrame
After running the code, your DataFrame will look like this:
| index | alimento | calorias | classificacao |
|---|---|---|---|
| 0 | iogurte | 40 | laticinio |
| 1 | sardinha | 30 | peixe |
| 2 | manteiga | 50 | gordura animal |
| 3 | maçã | 10 | fruta |
| 4 | milho | 10 | cereal |
Handling unexpected values
If your dataset includes food names not in the mapping dictionary, map() will return NaN for those rows. To set a default category (like "outro" for unlisted foods), chain the fillna() method:
alimentos['classificacao'] = alimentos['alimento'].map(classificacao_map).fillna('outro')
Alternative: Using replace()
You could also use replace() for this task, though it’s typically used to modify existing columns rather than create new ones. It still works here:
alimentos['classificacao'] = alimentos['alimento'].replace(classificacao_map)
The map() method is generally preferred for creating new columns since it’s more explicit about your intent.
Content from stack exchange, question author Reinaldo Chaves

