如何根据python中的第一个元素得到最大的3D矩阵

How to get a maximum of 3D matrix based on the first element in python

我有一个形状为 (3,2,2) 的 3D 矩阵。像这样:

t[0]=[2,4
      5,6]    

t[1]=[3,3
      2,3]

t[2]=[1,5
     4,7]

我想得到最大的 t 给我 6, 3, 76 是 [= 的最大值18=] 等等。

一个选项:你可以遍历数组并为每个子数组取最大值:

[np.max(x) for x in t]
# [6, 3, 7]

另一个选项:

t.reshape(3,4).max(axis = 1)
# array([6, 3, 7]

更简单的方法是:

t.max(axis = (1,2))
# array([6, 3, 7])

关于以上三种方法的一些基准:

%timeit [np.max(x) for x in t]
# 100000 loops, best of 3: 10.9 µs per loop

%timeit t.reshape(3,4).max(axis = 1)
# 100000 loops, best of 3: 2.75 µs per loop

%timeit t.max(axis = (1,2))
# 100000 loops, best of 3: 2.63 µs per loop