Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

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.

1 Answer

0 votes
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 [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 ])

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

Related questions

0 votes
1 answer
0 votes
4 answers

Browse Categories

...