gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:20:52 25 4
gpt4 key购买 nike

是否有一种从字符串数组中提取索引的便捷方法?我希望使用 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/

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