# Max of each 2D matrix in 4D NumPy array

1 view

I have the 4D array, which is defined as follows:

B = np.array(

[[[[0.5000, 0.5625],

[0.5000, 0.5625]],

[[1.2500, 0.5000],

[0.5625, 0.6875]],

[[0.5625, 0.6250],

[0.5000, 0.5625]]]]

)

I want to take a max of each 2D matrix, such that I get the result of:

array([0.5625, 1.250, 0.6250])

Similarly, I want to take the min of each 2D matrix, such that I get the result of:

array([0.5000, 0.5000, 0.5000])

However, when doing np.max(B, axis=0), np.max(B, axis=1), np.max(B, axis=2), or np.max(B, axis=3) -- none of these gives a right answer. Is there another argument I need to specify to do this operation?

The correct solution should not use any loops and ideally one function call.

by (36.8k points)

I think, issue is the misunderstanding of how a axis argument works. For most of these aggregation methods of axis keyword is a axis (or axes) to project along, i.e. these axes are "removed" from a result. So in this case you want to call something like:

In : B.max((0, 2, 3))

Out: array([0.5625, 1.25 , 0.625 ])

same thing for min

In : B.min((0, 2, 3))

Out: array([0.5, 0.5, 0.5])

Or you can call the numpy method directly

In : np.max(B, axis=(0, 2, 3))                                                                                     Out: array([0.5625, 1.25 , 0.625 ])

Do check out Data Science with Python course which helps you understand from scratch.