Max of each 2D matrix in 4D NumPy array

别说谁变了你拦得住时间么 提交于 2021-02-10 05:10:10

问题


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.


回答1:


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 ])



回答2:


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])


来源:https://stackoverflow.com/questions/63368978/max-of-each-2d-matrix-in-4d-numpy-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!