Numpy比较数组一次到多个标量
问题描述:
假设我有一个数组
a = np.array([1,2,3])
,我想将其与某个标量进行比较;像
and I want to compare it to some scalar; this works fine like
a == 2 # [False, True, False]
有没有一种方法可以同时进行多个标量的比较?比较两个数组时的默认行为是进行逐元素比较,但我希望将一个数组的每个元素与整个另一个数组进行逐元素比较,如下所示:
Is there a way I can do such a comparison but with multiple scalars at once? The default behavior when comparing two arrays is to do an elementwise comparison, but instead I want each element of one array to be compared elementwise with the entire other array, like this:
scalars = np.array([1, 2])
some_function(a, scalars)
[[True, False, False],
[False, True, False]]
很明显,我可以做到这一点,例如,使用for循环然后堆叠,但是有没有矢量化的方法来实现相同的结果?
Obviously I can do this, e.g., with a for loop and then stacking, but is there any vectorized way to achieve the same result?
答
numpy.equal.outer(scalars, a)
或调整尺寸并进行广播比较:
or adjust the dimensions and perform a broadcasted comparison:
scalars[:, None] == a