Numpy:将标签转换为索引
Numpy : convert labels into indexes
是否可以使用 numpy
将字符串向量转换为索引向量?
假设我有一个字符串数组,如 ['ABC', 'DEF', 'GHI', 'DEF', 'ABC']
等。我希望将其更改为一个整数数组,如 [0,1,2,1,0]
。可以使用 numpy 吗?我知道 Pandas
有一个 Series
class 可以做到这一点,感谢 this answer。 numpy
也有类似的东西吗?
编辑:
np.unique()
returns 所有元素的唯一值。我想要做的是将 Iris dataset 中的标签转换为索引,例如分别为 Iris-setosa
的 0、Iris-versicolor
的 1 和 Iris-virginica
的 2。有没有办法使用 numpy
来做到这一点?
使用numpy.unique
with parameter return_inverse=True
, but there is difference with handling NaN
s - check 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]
是否可以使用 numpy
将字符串向量转换为索引向量?
假设我有一个字符串数组,如 ['ABC', 'DEF', 'GHI', 'DEF', 'ABC']
等。我希望将其更改为一个整数数组,如 [0,1,2,1,0]
。可以使用 numpy 吗?我知道 Pandas
有一个 Series
class 可以做到这一点,感谢 this answer。 numpy
也有类似的东西吗?
编辑:
np.unique()
returns 所有元素的唯一值。我想要做的是将 Iris dataset 中的标签转换为索引,例如分别为 Iris-setosa
的 0、Iris-versicolor
的 1 和 Iris-virginica
的 2。有没有办法使用 numpy
来做到这一点?
使用numpy.unique
with parameter return_inverse=True
, but there is difference with handling NaN
s - check 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]