问题描述
我怎样才能获得的交叉点的两个numpy的阵列之间的指数?我可以用交叉值intersect1d
:
How can I get the indices of intersection points between two numpy arrays? I can get intersecting values with intersect1d
:
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])
但我怎么能得到的指数纳入中的值的
间
?
推荐答案
您可以使用由 in1d
产生的布尔数组索引的人气指数
。倒车 A
这样的指标是从不同的值:
You could use the boolean array produced by in1d
to index an arange
. Reversing a
so that the indices are different from the values:
>>> a[::-1]
array([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
>>> a = a[::-1]
intersect1d
仍返回相同的值...
intersect1d
still returns the same values...
>>> 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)
哪些可用于索引的范围:
Which can be used to index a range:
>>> 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])
要简化以上的,不过,你可以使用<$c$c>nonzero$c$c> - 这可能是最正确的做法,因为它返回 X
,是
统一列表的元组.. 。坐标:
To simplify the above, though, you could use nonzero
-- this is probably the most correct approach, because it returns a tuple of uniform lists of X
, Y
... coordinates:
>>> 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])
但请注意,在许多情况下,这是有道理只使用布尔数组本身,而不是将其转换成一组非布尔指数。
But note that under many circumstances, it makes sense just to use the boolean array itself, rather than converting it into a set of non-boolean indices.
最后,您还可以通过布尔数组<$c$c>argwhere$c$c>,其产生的方式略有不同形状的结果,这不是作为适合于索引,但可能是用于其它目的是有用的。
Finally, you can also pass the boolean array to argwhere
, which produces a slightly differently-shaped result that's not as suitable for indexing, but might be useful for other purposes.
>>> numpy.argwhere(numpy.in1d(a, b))
array([[0],
[3],
[8]])
这篇关于的Python:路口指数numpy的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!