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

如何在Pandas中对指定列分类并生成新的category列

方法1:使用map映射(推荐,性能更高)

先定义类型映射规则,未匹配到的内容统一填充为other即可,代码如下:

import pandas as pd

# 你本身的DataFrame构造步骤这里省略
category_map = {
    "shoes": "shoes",
    "sandal": "shoes",
    "vest": "vest",
    "tshirt": "tshirt"
}

df["category"] = df["type"].map(category_map).fillna("other")

方法2:使用apply自定义判断逻辑

如果后续分类规则需要频繁调整,也可以通过自定义函数实现:

def classify_category(type_val):
    if type_val in ("shoes", "sandal"):
        return "shoes"
    elif type_val in ("vest", "tshirt"):
        return type_val
    else:
        return "other"

df["category"] = df["type"].apply(classify_category)

两种方法运行后得到的DataFrame就和你给出的预期结果完全一致。

内容的提问来源于stack exchange,提问作者nomnom3214

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 06:54:04