Ch2231
Ch2231

Reputation: 171

Get aggregation of data from each numpy sub-array

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?

Upvotes: 1

Views: 84

Answers (2)

Crazy Coder
Crazy Coder

Reputation: 414

Use max in numpy:

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

-1 is your last dimension.

printing it:

  [8, 16]

Upvotes: 1

Akshay Sehgal
Akshay Sehgal

Reputation: 19322

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

Upvotes: 1

Related Questions