Skip to main content
 首页 » 编程设计

python之Numpy 3D 数组最大值

2025年05月04日21shanyou

import numpy as np 
a = np.array([[[ 0.25,  0.10 ,  0.50 ,  0.15], 
           [ 0.50,  0.60 ,  0.70 ,  0.30]], 
          [[ 0.25,  0.50 ,  0.20 ,  0.70], 
           [ 0.80,  0.10 ,  0.50 ,  0.15]]]) 

我需要在 a[i] 中找到最大值的行和列。 如果 i=0,a[0,1,2] 是最大值,所以我需要编写一个方法,将 [1,2] 作为 a[0] 中最大值的输出。有什么指点吗? 注意:np.argmax 展平 a[i] 二维数组,当使用 axis=0 时,它在 a[0] 的每一行中给出 max 的索引

请您参考如下方法:

您还可以将 argmax 与 unravel_index 一起使用:

def max_by_index(idx, arr): 
    return (idx,) + np.unravel_index(np.argmax(arr[idx]), arr.shape[1:]) 

例如

import numpy as np 
a = np.array([[[ 0.25,  0.10 ,  0.50 ,  0.15], 
               [ 0.50,  0.60 ,  0.70 ,  0.30]], 
              [[ 0.25,  0.50 ,  0.20 ,  0.70], 
               [ 0.80,  0.10 ,  0.50 ,  0.15]]]) 
 
def max_by_index(idx, arr): 
    return (idx,) + np.unravel_index(np.argmax(arr[idx]), arr.shape[1:]) 
 
 
print(max_by_index(0, a)) 

给予

(0, 1, 2)