You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas中依据指定列内容自动填充新列行数据?

How to Add a Classification Column Based on Food Names in 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:

indexalimentocaloriasclassificacao
0iogurte40laticinio
1sardinha30peixe
2manteiga50gordura animal
3maçã10fruta
4milho10cereal

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:50:49