Get aggregation of data from each numpy sub-array

Question:

I have such an array:

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]).reshape(2,2,4)

array([[[ 1,  2,  3,  4],
        [ 5,  6,  7,  8]],

       [[ 9, 10, 11, 12],
        [13, 14, 15, 16]]])

And I want to get to get the max for each of these sub-arrays:

arr[:,:,-1]

array([[ 4,  8],
       [12, 16]])

So I would want each of these sub-arrays converted to their max value. As result:

array([8, 16)]

How would I be able to do that without iterating?

Asked By: Ch2231

||

Answers:

Use max in numpy:

arr[:,:,-1].max(-1)

-1 is your last dimension.

printing it:

  [8, 16]
Answered By: Crazy Coder

IIUC you want the output to be [8,16] which is a max of the sub-arrays arr[:,:,-1] that you have computed. Try this –


arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]).reshape(2,2,4)

np.max(arr[:,:,-1],-1)
array([ 8, 16])
Answered By: Akshay Sehgal
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.