python - 字符串中的一个热点 - 获取唯一值列表中的索引

标签 python numpy one-hot-encoding

是否有一种从字符串数组中提取索引的便捷方法?我希望使用 NumPy 进行简单的单热编码。我有一种方法可以自行进行编码,但首先我需要一个要编码的索引列表。

获取排序后的唯一元素非常简单。

>>> vals = np.array(['a', 'b', 'c', 'b', 'a'])
>>> uniq = np.unique(vals)
array(['a', 'b', 'c'], dtype='<U1')

然后就会发生转换。首先,我考虑使用基本 Python 列表来使用 list.index,但这涉及将列表从 ndarray 转换为 list 并返回。我想有更好的解决方案。

我想到的是:

idx = [np.where(uniq == v) for v in vals]

但这会产生一个 nd 数组的数组。

自然地得到预期的输出:

[0, 1, 2, 1, 0]

最佳答案

设置return_inverse=True:

vals = np.array(['a', 'b', 'c', 'b', 'a'])
u, indices = np.unique(vals, return_inverse=True)

print(u)  # ['a' 'b' 'c']
print(indices)  # [0 1 2 1 0]

关于python - 字符串中的一个热点 - 获取唯一值列表中的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50791311/

相关文章:

python - pandas系列中的两列排序

python 字典列表如何合并键 :value where values are same?

python - numpy 中图像的 Mipmap?

python - 如何删除列或数据框中的括号

python - Windows Scipy 安装 : No Lapack/Blas Resources Found

pyspark - 将一次热编码后获得的稀疏向量转换为列

python - 我该如何修复 “TypeError: expected string or bytes-like object”

nlp - 如何处理包含名义数据的目标变量?

python-3.x - 使用分类数据集 : how to deal with different values (less number) in categorical data 进行 One-hot 编码

javascript - 避免对 jQuery sortable( ) 进行多次 AJAX 调用