python - NumPy 的 : convert labels into indexes

标签 python pandas numpy classification data-science

是否可以使用 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/

相关文章:

python - 使用带有特定单词的 pandas 提取句子

python - 如何获取pytorch中子数组的索引?

Python - 仅使用循环删除空格

python - Theano隐藏层激活函数

python - 通过for循环和exec()创建一系列映射

python - 如果使用 Python 值随着时间的推移停留在单个值,则使用 NaN 进行更改

python - 验证等于 33 : fails in R, 的三个立方体之和在 Python 中是否有效

python - 与 Jupyter Notebook 中动态更新的图形进行交互

python - 在 python 的 C 扩展中包含外部共享英特尔的 mkl 库

python - "pandas datetime convert to num"中的问题