Alan_AI
Alan_AI

Reputation: 1569

pythonic way for partwise max in a numpy array

I am wondering if there is a fast way to compute a partwise maximum in a numpy array. Example:

a = [1,2,3,4,5,6,7,8,9]

If we fix the part size to 3, I would want the answer to be:

b = [3,6,9]

where 3 is the maximum of the first part of a, [1,2,3], 6 is the maximum of the second part [4,5,6] and so on..

Upvotes: 4

Views: 93

Answers (2)

Fanchi
Fanchi

Reputation: 787

If you have a numpy array, you can reshape it to the part size as row length, now you have a 2d matrix, you can do row/column max.

Edit1: Took ajcr comment and added it to the code.

import numpy as np

a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
a = a.reshape((-1, 3))
print a.max(1)

Output:

[ 3  6  9 12]

Upvotes: 3

Ami Tavory
Ami Tavory

Reputation: 76346

Try reshaping, then taking the maximum:

import numpy as np

a = np.array([1,2,3,4,5,6,7,8,9])
>>> a.reshape((len(a) / 3, 3)).max(axis=1)
array([3, 6, 9])

If the array's length is not divisible by the number, your question needs more definition to say what you mean in this case.

Edit @ajcr in the comments below shows a much better way to reshape:

>>> a.reshape((-1, 3)).max(axis=1)

Upvotes: 3

Related Questions