寻找最快的方法来找到相等长度的两个数组在numpy中的确切重叠 [英] Looking for the fastest way to find the exact overlap between two arrays of equal length in numpy

查看:113
本文介绍了寻找最快的方法来找到相等长度的两个数组在numpy中的确切重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am looking for the optimal (fastest) way to find the exact overlap between two arrays in numpy. Given two arrays x and 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)

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

What I want to get is, an array of the same length that contains only the numbers from both vectors that are equal:

array([1,0,0,0,5,0,0,4])

首先我尝试了

x&y
array([1,0,0,0,5,0,6,4])

然后我意识到,如果两个数字> 0,这始终是正确的.

Then I realised that this is always true for two numbers if they are > 0.

推荐答案

result = numpy.where(x == y, x, 0)

看看 numpy.where 说明文件.基本上,对于条件anumpy.where(a, b, c)返回形状为a的数组,其值分别为bc,具体取决于a的相应元素是否为true. bc可以是标量.

Have a look at numpy.where documentation for explanation. Basically, numpy.where(a, b, c), for a condition a returns an array of shape a, and with values from b or c, depending upon whether the corresponding element of a is true or not. b or c can be scalars.

顺便说一句,对于两个正数,x & y不一定是始终为真".对于xy中的元素,它按位和:

By the way, x & y is not necessarily "always true" for two positive numbers. It does bitwise-and for elements in x and 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]

这是因为x中每个元素的按位表示形式为1,后跟n零,而y中的相应元素为n 1s.通常,对于两个非零数字aba & b可以等于零或非零,但不一定等于ab.

This is because the bitwise representation of each element in x is of the form 1 followed by n zeros, and the corresponding element in y is n 1s. In general, for two non-zero numbers a and b, a & b may equal zero, or non-zero but not necessarily equal to either a or b.

这篇关于寻找最快的方法来找到相等长度的两个数组在numpy中的确切重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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