【问题标题】:How to find the x-axis and y-axis index of a value in 2-dimensional array?如何在二维数组中找到一个值的 x 轴和 y 轴索引?
【发布时间】:2024-05-16 06:25:02
【问题描述】:

堆栈溢出!我在查找二维数组的索引方面遇到了困难。我试图在数组中找到最小值并返回相应的 (x,y) 索引。

我曾尝试同时使用np.argmin(a,axis=0)np.argmin(a,axis=1) 分别查找x 和y 索引。

import numpy as np
a =  ([[3.2,  0,  0.5, 5.8], 
       [   6,  1,  6.2, 7.1],
       [ 3.8,  5,  2.7, 3.7]])
def axis(a):
    x_min = np.argmin(a,axis = 0)
    y_min = np.argmax(a,axis = 1)

    return x_min,y_min

a1,a2=axis(a)

print('x is ',a1)
print('y is ',a2)

输出应该是:x is 0y is 1,因为零是数组中的最小值。 然而,实际的输出是一个整数列表。

【问题讨论】:

  • 不应该返回索引(0,0) 因为-3.2 是最小值吗?
  • 抱歉,忘记换标志了。

标签: python arrays python-3.x numpy indices


【解决方案1】:

argmin 不带轴是a 的扁平版本中的位置:

In [200]: a =np.array([[-3.2,  0,  0.5, 5.8],  
     ...:        [   6,  1,  6.2, 7.1], 
     ...:        [ 3.8,  5,  2.7, 3.7]])                                                                     
In [201]: np.argmin(a, axis=0)                                                                               
Out[201]: array([0, 0, 0, 2])   # smallest in each of the 4 columns
In [202]: np.argmin(a, axis=1)                                                                               
Out[202]: array([0, 1, 2])      # smallest in each of the 3 rows

unravel 可以将其转换为二维索引:

In [203]: np.argmin(a)                                                                                       
Out[203]: 0
In [204]: np.unravel_index(np.argmin(a), a.shape)                                                            
Out[204]: (0, 0)
In [205]: np.unravel_index(1, a.shape)                                                                       
Out[205]: (0, 1)

这种用法记录在argmin:

Indices of the minimum elements of a N-dimensional array:

>>> ind = np.unravel_index(np.argmin(a, axis=None), a.shape)
>>> ind
(0, 0)
>>> a[ind]
10

【讨论】:

    【解决方案2】:

    获取最小值/最大值的索引

    import numpy as np
    a =([[-3.2,  0,  0.5, 5.8], 
           [   6,  1,  6.2, 7.1],
           [ 3.8,  5,  2.7, 3.7]])
    xyMin = np.argwhere(a == np.min(a)) #Indices of Minimum
    xyMax = np.argwhere(a == np.max(a)) #Indices of Maximum
    
    xIndex = xyMin[0][0] #x-index
    yIndex = xyMin[0][1] #y-index
    

    或者您可以使用 .flatten() 将二维数组转换为一维数组,如下所示

    xyMin = np.argwhere(a == np.min(a)).flatten() #Indices of Minimum
    xIndex = xyMin[0] #x-index
    

    【讨论】:

    • 如何将它们分开得到,例如x是1,y是0而不是(0,1)?
    • @0verl0rd21 编辑了代码以访问单个索引。