如何获得两个numpy数组之间的交叉点索引?我可以intersect1d
得到相交值:Python:交叉索引numpy数组
import numpy as np
a = np.array(xrange(11))
b = np.array([2, 7, 10])
inter = np.intersect1d(a, b)
# inter == array([ 2, 7, 10])
但我怎么能拿到指标进入价值a
在inter
?
如何获得两个numpy数组之间的交叉点索引?我可以intersect1d
得到相交值:Python:交叉索引numpy数组
import numpy as np
a = np.array(xrange(11))
b = np.array([2, 7, 10])
inter = np.intersect1d(a, b)
# inter == array([ 2, 7, 10])
但我怎么能拿到指标进入价值a
在inter
?
您可以使用in1d
生成的布尔数组索引arange
。倒车a
从而使指数是不同的值:
>>> a[::-1]
array([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
>>> a = a[::-1]
intersect1d
仍返回相同的值...
>>> numpy.intersect1d(a, b)
array([ 2, 7, 10])
但in1d
返回一个布尔值数组:
>>> numpy.in1d(a, b)
array([ True, False, False, True, False, False, False, False, True,
False, False], dtype=bool)
哪可用于对一个范围进行索引:
>>> numpy.arange(a.shape[0])[numpy.in1d(a, b)]
array([0, 3, 8])
>>> indices = numpy.arange(a.shape[0])[numpy.in1d(a, b)]
>>> a[indices]
array([10, 7, 2])
为了简化以上,不过,你可以使用nonzero
- 这可能是最正确的做法,因为它返回的X
,Y
统一列表的元组...坐标:
>>> numpy.nonzero(numpy.in1d(a, b))
(array([0, 3, 8]),)
或者等价地:
>>> numpy.in1d(a, b).nonzero()
(array([0, 3, 8]),)
结果可以用作索引,以相同的形状a
,没有任何问题的阵列。
>>> a[numpy.nonzero(numpy.in1d(a, b))]
array([10, 7, 2])
但请注意,在很多情况下,它是有道理的只是使用布尔数组本身,而不是将其转换为一组非布尔指数。
最后,您还可以将布尔数组传递给argwhere
,这会产生稍微不同的结果,但不适合索引,但可能对其他用途有用。
>>> numpy.argwhere(numpy.in1d(a, b))
array([[0],
[3],
[8]])
如果你需要得到唯一值由intersect1d给出:
import numpy as np
a = np.array([range(11,21), range(11,21)]).reshape(20)
b = np.array([12, 17, 20])
print(np.intersect1d(a,b))
#unique values
inter = np.in1d(a, b)
print(a[inter])
#you can see these values are not unique
indices=np.array(range(len(a)))[inter]
#These are the non-unique indices
_,unique=np.unique(a[inter], return_index=True)
uniqueIndices=indices[unique]
#this grabs the unique indices
print(uniqueIndices)
print(a[uniqueIndices])
#now they are unique as you would get from np.intersect1d()
输出:
[12 17 20]
[12 17 20 12 17 20]
[1 6 9]
[12 17 20]
让我们通过这一步一步来。
首先,我们创建带零点的numpy的阵列c中使用交叉索引
c[inter] = 1
print c
>>>[ 0. 0. 1. 0. 0. 0. 0. 1. 0. 0. 1.]
的最后一步,使用特性
c = np.zeros(len(a))
print c
>>> [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
其次,改变数组值它将返回索引的非零项
inter_with_idx = np.nonzero(c)
print inter_with_idx
>>>array([ 2, 7, 10])
[1] numpy.nonzero
那么粗糙,但它的工作原理:) 更容易在八度: [除指数A indexB] =相交(A,B) – invis 2012-07-14 13:15:49
谢谢你很多关于你的答案 ! in1d和intersect1d的 – invis 2012-07-14 18:32:48
不一样。 intersect1d给出了唯一的值,in1d给出了所有的交集,所以这个答案不会一直工作。 – Rik 2016-09-20 02:50:35