首页 > 解决方案 > 如何通过numpy中的指定数组获取索引

问题描述

我有以下数组。我想通过数组的搜索键提取索引。 np.array([[1,2],[2,2], [3,2], [2,2]])的shep是(4, 2)。所以搜索的结果[2, 2]应该返回[1, 3]哪个是 的索引[2, 2]np.argwhere是一个强大的功能,但是,如何将其用于我的目的?

In [31]: d=np.array([[1,2],[2,2], [3,2], [2,2]])    
In [32]: d
Out[32]:
array([[1, 2],
       [2, 2],
       [3, 2],
       [2, 2]])

In [33]: np.where(d==np.array([2,2]))
Out[33]: (array([0, 1, 1, 2, 3, 3]), array([1, 0, 1, 1, 0, 1]))
In [34]: np.argwhere(d==np.array([2,2]))
Out[34]:
array([[0, 1],
       [1, 0],
       [1, 1],
       [2, 1],
       [3, 0],
       [3, 1]])

标签: pythonnumpy

解决方案


Use np.all(..., axis=1) to reduce the boolean array over the second axis, then use np.where:

np.where((d == [2, 2]).all(1))[0]
# array([1, 3])

推荐阅读