Search code examples
pythonnumpy

How to return the highest value from a multi dimensional array?


Say I have a multi dimensional array like the following:

[
   [.1, .2, .9],
   [.3, .4, .5],
   [.2, .4, .8]
]

What would be the best* way to return a single dimension array that contains the highest value from each sub-array ([.9,.5,.8])? I assume I could do it manually doing something like below:

newArray = []
for subarray in array:
   maxItem = 0
   for item in subarray:
       if item > maxItem:
           maxItem = item
   newArray.append(maxItem)

But I'm curious if there is a cleaner way to do this?

*In this case best = fewest lines of code


Solution

  • Since you mentioned in a comment that you are using numpy ...

    >>> import numpy as np
    >>> a = np.random.rand(3,3)
    >>> a
    array([[ 0.43852835,  0.07928864,  0.33829191],
           [ 0.60776121,  0.02688291,  0.67274362],
           [ 0.2188034 ,  0.58202254,  0.44704166]])
    >>> a.max(axis=1)
    array([ 0.43852835,  0.67274362,  0.58202254])
    

    edit: the documentation is here