微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

一般来说,我是 numpy 和 python 的新手,我正在寻找给定 3D 数组的每个 2D 子数组的最小值。例如:

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

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

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

给出了这个结果: 3D Matrix

我正在寻找的结果是每个二维数组中最小元素的索引,例如:

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

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

感谢任何帮助,谢谢!

解决方法

In [716]: arr
Out[716]: 
array([[[inf,5.,4.,1.,5.],[ 3.,inf,2.,9.,3.],[ 9.,7.,6.,[ 5.,2.],[ 4.,inf]],[[inf,0.,[ 8.,1.],[ 7.,8.,3.,[ 6.,8.],[ 1.,4.],[ 0.,inf]]],dtype=float32)

将其重塑为二维:

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

将这些索引转换为二维:

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。