如何在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
相关产品推荐
相关产品推荐

