使用Python高效的方法来执行元素“插入"操作使用numpy [英] Pythonic and efficient way to do an elementwise "in" using numpy
问题描述
我正在寻找一种有效获取布尔数组的方法,其中给定两个大小相等的数组 a
和 b
,如果相应的元素为true,则每个元素为true a
的元素出现在 b
的相应元素中.
I'm looking for a way to efficiently get an array of booleans, where given two arrays with equal size a
and b
, each element is true if the corresponding element of a
appears in
the corresponding element of b
.
例如,以下程序:
a = numpy.array([1, 2, 3, 4])
b = numpy.array([[1, 2, 13], [2, 8, 9], [5, 6], [7]])
print(numpy.magic_function(a, b))
应该打印
[True, True, False, False]
请记住,此功能应等同于
Keep in mind this function should be the equivalent of
[x in y for x, y in zip(a, b)]
仅当 a
和 b
很大且 b
的每个元素为相当小.
Only numpy
-optimized for cases when a
and b
are big, and each element of b
is reasonably small.
推荐答案
要利用NumPy的广播规则,应首先使数组 b
平方,这可以使用 itertools.izip_longest
:
To take advantage of NumPy's broadcasting rules you should make array b
squared first, which can be achieved using itertools.izip_longest
:
from itertools import izip_longest
c = np.array(list(izip_longest(*b))).astype(float)
导致:
array([[ 1., 2., 5., 7.],
[ 2., 8., 6., nan],
[ 13., 9., nan, nan]])
然后,通过执行 np.isclose(c,a)
,您将获得一个二维布尔数组,显示每个 c [:, i]
和 a [i]
,根据广播规则,给出:
Then, by doing np.isclose(c, a)
you get a 2D array of Booleans showing the difference between each c[:, i]
and a[i]
, according to the broadcasting rules, giving:
array([[ True, True, False, False],
[False, False, False, False],
[False, False, False, False]], dtype=bool)
可以用来获取答案的人
np.any(np.isclose(c, a), axis=0)
#array([ True, True, False, False], dtype=bool)
这篇关于使用Python高效的方法来执行元素“插入"操作使用numpy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!