Numpy比较数组一次到多个标量 [英] Numpy compare array to multiple scalars at once

查看:100
本文介绍了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

这篇关于Numpy比较数组一次到多个标量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆