我正在寻找最佳(最快)的方法来找到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,则总是如此.
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两个正数不一定"总是正确".它按位与在元素x和y:
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零,相应的元素y是n1.一般地,对于两个非零数字a和b,a & b可等于零,或非零但不一定等于任一a或b.
| 归档时间: |
|
| 查看次数: |
2542 次 |
| 最近记录: |