gpt4 book ai didi

python - NumPy 的 : convert labels into indexes

转载 作者:太空狗 更新时间:2023-10-30 02:53:18 25 4
gpt4 key购买 nike

是否可以使用 numpy 将字符串向量转换为索引向量?

假设我有一个字符串数组,如 ['ABC', 'DEF', 'GHI', 'DEF', 'ABC'] 等。我希望将其更改为数组像 [0,1,2,1,0] 这样的整数。可以使用 numpy 吗?我知道 Pandas 有一个可以执行此操作的 Series 类,由 this answer 提供. numpy 也有类似的东西吗?

编辑: np.unique() 返回所有元素的唯一值。我要做的是转换 Iris dataset 中的标签到索引,例如 Iris-setosa 为 0,Iris-versicolor 为 1,Iris-virginica 为 2。有没有办法使用 numpy 来做到这一点?

最佳答案

使用numpy.unique带有参数 return_inverse=True,但处理 NaN 时存在差异 - 检查 factorizing values :

L = ['ABC', 'DEF', 'GHI', 'DEF', 'ABC']

print (np.unique(L, return_inverse=True)[1])
[0 1 2 1 0]

Pandas factorize也适用于列表或数组:

print (pd.factorize(L)[0])
[0 1 2 1 0]

关于python - NumPy 的 : convert labels into indexes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50129663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com