如何找到二维数组中值的x轴和y轴索引?

时间:2019-08-13 05:07:31

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

StackOverflow!我遇到了有关查找二维数组索引的问题。我试图在数组中找到最小值,并返回相应的(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,因为零是数组中的最小值。 但是,实际输出是整数列表。

2 个答案:

答案 0 :(得分:0)

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可以将其转换为2d索引:

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

答案 1 :(得分:-1)

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

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()将2D数组转换为一维,如下所示

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