Yosh
Yosh

Reputation: 2742

Most pythonic way to find the maximum elements out of list of np.array?

I have a list of np.array, mya = [a0,...,an] (all of which have the same shape and dtype). Say ai has the shape ai = array[xi0,xi1,..,xim]. I want to get

[max((a[i] for a in mya)) for i in range(m)]

. For example, let x=np.array([3,4,5]), y=np.array([2,50,-1]) and z=np.array([30,0,3]) then for mya = [x,y,z], I want [30,50,5] (or np.array equivalent).

Giving m by m=len(mya[0]), my code above does work, but it seems way too tedious. What are the suggested ways to achieve this?

Upvotes: 0

Views: 106

Answers (2)

Yosh
Yosh

Reputation: 2742

As @Ruben_Bermudez suggested, np.amax was just what I was looking for.

np.amax, scipy documentation provided here, accepts an array-like data as input and returns "the maximum of an array or maximum along an axis." Among its optional parameters is axis, which specifies the axis along which to find maximum.

By default, input is flattened, so

np.amax(mya) # => 50

Specifying axis=0

np.amax(mya,axis=0)  # np.array([30,50,5])

and this was what I wanted.

Sorry for the mess.

Upvotes: 0

Ruben Bermudez
Ruben Bermudez

Reputation: 2323

In numpy, numpy.amax(myarray) give you the maximum of myarray. If you look for the maximum of each list/array of first dimmension, you can set also the axis you want. In this case, it should be:

x=np.array([3,4,5])
y=np.array([2,50,-1])
z=np.array([30,0,3])
mya = [x,y,z] 
maximum = np.amax(mya, axis=0)
# maximum will store a list as [maximumofx, maximumofy, maximumofz] -> [30,50,5]

See docs

Upvotes: 2

Related Questions