python - 在 numpy 中向量化简单的 for 循环

标签 python arrays numpy for-loop vectorization

我对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/

相关文章:

python - 从发送模型中调用 django post_save?

java - 比较单个二维数组中的两行

python - 计算具有不同 x 值的 y 值的平均值

numpy - 基于放置在像素上的小掩码分配值

Python - 使用多处理和按键检测

Python 从另一个多处理函数调用一个多处理函数。

c++ - C++检查unordered_map/map的std::array包含相同的元素类型

java - 对第二个单词进行排序

python - 划分 NumPy 数组时出现 MemoryError

python - 是否可以在 dataframe.pivot_table 中显示 2 个最大值? Pandas python