假设我有一个这样的数组:
import numpy as np
base_array = np.array([-13, -9, -11, -3, -3, -4, 2, 2,
2, 5, 7, 7, 8, 7, 12, 11])
假设我想知道:
base_array
中有多少个元素大于4?这可以通过利用广播来简单实现:np.sum(4 < base_array)
答案是7
。现在,假设我想要对一个数组进行比较,而不是与单个值进行比较。换句话说,对于comparison_array
中的每个值c
,找出有多少个base_array
元素大于c
。如果我以天真的方式这样做,显然会失败,因为它不知道如何正确广播:
comparison_array = np.arange(-13, 13)
comparison_result = np.sum(comparison_array < base_array)
输出:
Traceback (most recent call last):
File "<pyshell#87>", line 1, in <module>
np.sum(comparison_array < base_array)
ValueError: operands could not be broadcast together with shapes (26,) (16,)
如果我可以让
comparison_array
的每个元素都广播到base_array
的形状上,那么就能解决这个问题。但我不知道如何进行“逐元素广播”。现在,我知道如何使用列表推导为两种情况都实现这一点:
first = sum([4 < i for i in base_array])
second = [sum([c < i for i in base_array])
for c in comparison_array]
print(first)
print(second)
输出:
7
[15, 15, 14, 14, 13, 13, 13, 13, 13, 12, 10, 10, 10, 10, 10, 7, 7, 7, 6, 6, 3, 2, 2, 2, 1, 0]
但是众所周知,在处理大型数组时,这种方法比正确进行向量化的numpy
实现慢了数个数量级。那么,我应该如何在numpy
中快速完成此操作呢?理想情况下,这种解决方案应该适用于任何广播可行的操作,而不仅仅是在此示例中的大于或小于运算。