You need to enable JavaScript to run this app. Python有没有内置函数可将行类别转换为按字母排序的分类列?
优惠活动
大模型
产品
解决方案
定价
更多

Python有没有内置函数可将行类别转换为按字母排序的分类列?

问题解答

Python 标准库没有提供可以直接实现该需求的内置函数,你可以通过简单的原生代码实现,也可以借助第三方数据处理库的现成接口完成。

纯原生Python实现(无额外依赖)

仅用几行代码就可以完成转换:

mappingCategory = ["Animal", "Plant", "Animal", "Human", "Plant"]
# 第一步获取按字母排序的唯一类别列表
sorted_unique_cats = sorted(set(mappingCategory))
# 第二步生成目标二维数组
res = [[1 if item == cat else 0 for cat in sorted_unique_cats] for item in mappingCategory]

执行后res的结果就是你需要的[[1, 0, 0], [0, 0, 1], [1, 0, 0], [0, 1, 0], [0, 0, 1]]。

第三方库实现(允许引入依赖时可选)

如果项目可以引入第三方依赖,也可以用成熟库的现成方法:

scikit-learn 实现

from sklearn.preprocessing import OneHotEncoder
import numpy as np

mappingCategory = ["Animal", "Plant", "Animal", "Human", "Plant"]
encoder = OneHotEncoder(sparse_output=False, categories='auto')
res = encoder.fit_transform(np.array(mappingCategory).reshape(-1, 1)).tolist()

pandas 实现

import pandas as pd

mappingCategory = ["Animal", "Plant", "Animal", "Human", "Plant"]
res = pd.get_dummies(mappingCategory, dtype=int).sort_index(axis=1).values.tolist()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 23:45:03