【问题标题】:numpy - return first index of element in array [duplicate]numpy - 返回数组中元素的第一个索引[重复]
【发布时间】:2018-04-06 00:42:45
【问题描述】:

返回变量和 ndarray 中元素之间第一次匹配的索引的最快方法是什么?我看到 numpy.where 使用了很多,但它返回所有索引。

match = 5000
zArray = np.array([[0,1200,200],[1320,24,5000],[5000,234,5230]])

>array([[   0, 1200,  200],
   [1320,   24, 5000],
   [5000,  234, 5230]])

numpy.where(zArray==match)
>(array([1, 2], dtype=int64), array([2, 0], dtype=int64))

我希望返回第一个索引,即仅 [1,2]。但 numpy.where 同时返回 [1,2] 和 [2,0]

【问题讨论】:

  • 你会如何定义 first 匹配?行专业还是列专业?
  • 谢谢大家,我需要澄清一下..
  • 请注意,您的示例数组恰好设置为结果中的两个数组似乎是您正在寻找的两个 x、y 索引对。相反,这些是匹配项的 [x1, x2] 和 [y1, y2] 索引。尝试例如[[0,5000,200],[1320,24,1200],[234,5000,5230]] 来看看。
  • 只是为了重复@Evert 提到的内容,我相信"I'd like the first index returned, i.e. just [1,2]. but numpy.where returns both [1,2] and [2,0]" 需要修改。

标签: python arrays numpy


【解决方案1】:

您可以使用np.argwhere 将匹配的索引打包为一个二维数组,每行保存每个匹配的索引,然后索引到第一行,就像这样 -

np.argwhere(zArray==match)[0]

或者,使用argmax 更快地获取扁平版本上第一个匹配项的索引,使用np.unravel_index 获取每个维度索引元组的索引 -

np.unravel_index((zArray==match).argmax(), zArray.shape)

示例运行 -

In [100]: zArray
Out[100]: 
array([[   0, 1200, 5000], # different from sample for a generic one
       [1320,   24, 5000],
       [5000,  234, 5230]])

In [101]: match
Out[101]: 5000

In [102]: np.argwhere(zArray==match)[0]
Out[102]: array([0, 2])

In [103]: np.unravel_index((zArray==match).argmax(), zArray.shape)
Out[103]: (0, 2)

运行时测试-

In [104]: a = np.random.randint(0,100,(1000,1000))

In [105]: %timeit np.argwhere(a==50)[0]
100 loops, best of 3: 2.41 ms per loop

In [106]: %timeit np.unravel_index((a==50).argmax(), a.shape)
1000 loops, best of 3: 493 µs per loop

【讨论】:

  • argwhere 只是transpose(where(...))。它对于第一次出现很方便,但不会进行任何类型的短路。 argmax 可能会使布尔匹配短路(我知道 nan 测试确实如此)。
  • 感谢迪瓦卡。这很好用,非常适合我的需求。
猜你喜欢
  • 2013-08-07
  • 1970-01-01
  • 2018-10-25
  • 2011-01-20
  • 1970-01-01
  • 1970-01-01
  • 2021-08-21
  • 2017-12-01
  • 2021-08-23
相关资源
最近更新 更多