我对numpy还很陌生,出于性能原因,我正在尝试矢量化一个简单的for循环,但我似乎无法想出一个解决方案。我有一个包含唯一单词的 numpy 数组,对于每个单词,我需要它们在另一个 numpy 数组(称为 array_to_compare)中出现的次数。该数字被传递到第三个 numpy 数组,该数组与唯一单词数组具有相同的形状。 这是包含 for 循环的代码:
import numpy as np
unique_words = np.array(['a', 'b', 'c', 'd'])
array_to_compare = np.array(['a', 'b', 'a', 'd'])
vector_array = np.zeros(len(unique_words))
for word in np.nditer(unique_words):
counter = np.count_nonzero(array_to_compare == word)
vector_array[np.where(unique_words == word)] = counter
vector_array = [2. 1. 0. 1.] #the desired output
我用 np.where 和 np.isin 尝试过,但没有得到想要的结果。我很感谢您的帮助!
最佳答案
我可能会使用计数器
和列表理解来解决这个问题:
In [1]: import numpy as np
...:
...: unique_words = np.array(['a', 'b', 'c', 'd'])
...: array_to_compare = np.array(['a', 'b', 'a', 'd'])
In [2]: from collections import Counter
In [3]: counter = Counter(array_to_compare)
In [4]: counter
Out[4]: Counter({'a': 2, 'b': 1, 'd': 1})
In [5]: vector_array = np.array([counter[key] for key in unique_words])
In [6]: vector_array
Out[6]: array([2, 1, 0, 1])
组装计数器
是在线性时间内完成的,并且迭代unique_words
也是线性的。
关于python - 在 numpy 中向量化简单的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68165472/