Skip to main content
 首页 » 编程设计

python之我如何从 numpy 二维数组中找到大于特殊数字的元素索引

2024年10月17日16bluestorm

我想从 numpy 二维数组中找到大于 2 的元素的索引。

像这样

import numpy as np 
a = np.array([[1,2,3],[4,5,6]]) 
 
#  find indices of element that bigger than 2 
# result  = [[0,2],[[1,0],[1,1],[1,2]] 

请您参考如下方法:

您可以使用 np.where(),它将以元组模式(单独的轴)为您提供预期的索引:

In [6]: np.where(a>2) 
Out[6]: (array([0, 1, 1, 1]), array([2, 0, 1, 2])) 

或者直接np.argwhere():

In [5]: np.argwhere(a>2) 
Out[5]:  
array([[0, 2], 
       [1, 0], 
       [1, 1], 
       [1, 2]])