Joseph Konan
Joseph Konan

Reputation: 696

Max of each 2D matrix in 4D NumPy array

I have a 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 the max of each 2D matrix, such that I get a result of:

array([0.5625, 1.250, 0.6250])

Similarly, I want to take the min of each 2D matrix, such that I get a 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 the 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.

Upvotes: 2

Views: 411

Answers (2)

David Hoffman
David Hoffman

Reputation: 2343

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

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

same thing for min

In [8]: B.min((0, 2, 3))                                                                                                            
Out[8]: array([0.5, 0.5, 0.5])

Or you can call the numpy method directly

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

Upvotes: 3

ggorlen
ggorlen

Reputation: 56905

You can reshape it into a 2d array of the desired subarrays, then apply your max or min function on each subarray:

>>> B.reshape(3, 4)
array([[0.5   , 0.5625, 0.5   , 0.5625],
       [1.25  , 0.5   , 0.5625, 0.6875],
       [0.5625, 0.625 , 0.5   , 0.5625]])
>>> B.reshape(3, 4).max(axis=1)
array([0.5625, 1.25  , 0.625 ])
>>> B.reshape(3, 4).min(axis=1)
array([0.5, 0.5, 0.5])

Upvotes: 2

Related Questions