寻找找到numpy中两个相等长度数组之间精确重叠的最快方法

Adr*_*ian 3 python numpy

我正在寻找最佳(最快)的方法来找到numpy中两个数组之间的确切重叠.给定两个数组x和y

x = array([1,0,3,0,5,0,7,4],dtype=int)
y = array([1,4,0,0,5,0,6,4],dtype=int)
Run Code Online (Sandbox Code Playgroud)

我想得到的是一个长度相同的数组,只包含两个相等的数字:

array([1,0,0,0,5,0,0,4])
Run Code Online (Sandbox Code Playgroud)

首先我试过了

x&y
array([1,0,0,0,5,0,6,4])
Run Code Online (Sandbox Code Playgroud)

然后我意识到,如果两个数字> 0,则总是如此.

Alo*_*hal 6

result = numpy.where(x == y, x, 0)
Run Code Online (Sandbox Code Playgroud)

看看numpy.where文档的解释.基本上,numpy.where(a, b, c)对于条件,a返回一个形状数组a,并使用b或的值c,这取决于相应的元素是否a为真. b或者c可以是标量.

顺便说一句,x & y两个正数不一定"总是正确".它按位与在元素xy:

x = numpy.array([2**p for p in xrange(10)])
# x is [  1   2   4   8  16  32  64 128 256 512]
y = x - 1
# y is [  0   1   3   7  15  31  63 127 255 511]
x & y
# result: [0 0 0 0 0 0 0 0 0 0]
Run Code Online (Sandbox Code Playgroud)

这是因为每个元素的按位表示x形式1后跟n零,相应的元素yn1.一般地,对于两个非零数字ab,a & b可等于零,或非零但不一定等于任一ab.