从 3D 数组中查找每个 2D 数组中最小值的索引

Finding the indices of the minimum in each 2D array from a 3D array

我是 numpy 的新手,python 总体而言,我希望在给定 3D 数组的情况下找到每个 2D 子数组的最小值。例如:

# construct an example 3D array
a = np.array([[5,4,1,5], [0,1,2,3], [3,2,8,1]]).astype(np.float32)
b = np.array([[3,2,9,3], [8,6,5,3], [6,7,2,8]]).astype(np.float32)
c = np.array([[9,7,6,5], [4,7,6,3], [1,2,3,4]]).astype(np.float32)
d = np.array([[5,4,9,2], [4,2,6,1], [7,5,9,1]]).astype(np.float32)
e = np.array([[4,5,2,9], [7,1,5,8], [0,2,6,4]]).astype(np.float32)

a = np.insert(a, 0, [np.inf]*len(a), axis=1)
b = np.insert(b, 1, [np.inf]*len(b), axis=1)
c = np.insert(c, 2, [np.inf]*len(c), axis=1)
d = np.insert(d, 3, [np.inf]*len(d), axis=1)
e = np.insert(e, 4, [np.inf]*len(e), axis=1)

arr = np.swapaxes(np.dstack((a,b,c,d,e)), 1, 2)
print(arr) 

给出了这个结果: 3D Matrix

我要查找的结果是每个二维数组中最小元素的索引,类似于:

[[0, 0, 3], # corresponding to the coordinates of element with value 1 in the first 2D array
 [1, 0, 1], # corresponding to the coordinates of element with value 0 in the second 2D array
 [2, 4, 0]] # corresponding to the coordinates of element with value 0 in the third 2D array

或类似的东西。我计划使用索引来获取该值,然后用无限值替换该 2D 子数组中的列和行,以找到下一个不在同一 row/column.

中的最小值

感谢任何帮助,谢谢!

In [716]: arr
Out[716]: 
array([[[inf,  5.,  4.,  1.,  5.],
        [ 3., inf,  2.,  9.,  3.],
        [ 9.,  7., inf,  6.,  5.],
        [ 5.,  4.,  9., inf,  2.],
        [ 4.,  5.,  2.,  9., inf]],

       [[inf,  0.,  1.,  2.,  3.],
        [ 8., inf,  6.,  5.,  3.],
        [ 4.,  7., inf,  6.,  3.],
        [ 4.,  2.,  6., inf,  1.],
        [ 7.,  1.,  5.,  8., inf]],

       [[inf,  3.,  2.,  8.,  1.],
        [ 6., inf,  7.,  2.,  8.],
        [ 1.,  2., inf,  3.,  4.],
        [ 7.,  5.,  9., inf,  1.],
        [ 0.,  2.,  6.,  4., inf]]], dtype=float32)

将其重塑为 2d:

In [717]: idx = np.argmin(arr.reshape(3,-1),1)
In [718]: idx
Out[718]: array([ 3,  1, 20])

将这些索引转换为 2d:

In [719]: np.unravel_index(idx,(5,5))
Out[719]: (array([0, 0, 4]), array([3, 1, 0]))

这可以进一步处理以获得您想要的值 - 转置并添加 [0,1,2]

In [720]: np.transpose(np.vstack((np.arange(3),_)))
Out[720]: 
array([[0, 0, 3],
       [1, 0, 1],
       [2, 4, 0]])