gpt4 book ai didi

python - 将字符串列表(索引)转换为 Numpy 数组

转载 作者:行者123 更新时间:2023-11-28 22:28:05 26 4
gpt4 key购买 nike

我有一个列表,其中每个值只显示一个,我有另一个列表,其中包含标记化 numpy 数组的所需顺序。

例如:

sorted_values = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
a = ['a', 'c', 'g']
b = ['e']

我想像这样将 a 和 b(高效地)转换为 numpy 数组:

at = [1,0,1,0,0,0,1]
bt = [0,0,0,0,1,0,0]

有什么有效的方法吗?

最佳答案

利用第一个数组已经排序的事实,我们可以使用 np.searchsorted为了效率-

at = np.zeros(len(sorted_values), dtype=int)
bt = at.copy()
at[np.searchsorted(sorted_values, a)] = 1
bt[np.searchsorted(sorted_values, b)] = 1

关于python - 将字符串列表(索引)转换为 Numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43745878/

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