petrichor
petrichor

Reputation: 6569

Comparing elements of an array to a scalar and getting the max in Python

I want to compare the elements of an array to a scalar and get an array with the maximum of the compared values. That's I want to call

import numpy as np
np.max([1,2,3,4], 3)

and want to get

array([3,3,3,4])

But I get

ValueError: 'axis' entry is out of bounds

When I run

np.max([[1,2,3,4], 3])

I get

[1, 2, 3, 4]

which is one of the two elements in the list that is not the result I seek for. Is there a Numpy solution for that which is fast as the other built-in functions?

Upvotes: 32

Views: 25614

Answers (2)

askewchan
askewchan

Reputation: 46530

This is already built into numpy with the function np.maximum:

a = np.arange(1,5)
n = 3

np.maximum(a, n)
#array([3, 3, 3, 4])

This doesn't mutate a:

a
#array([1, 2, 3, 4])

If you want to mutate the original array as in @jamylak's answer, you can give a as the output:

np.maximum(a, n, a)
#array([3, 3, 3, 4])

a
#array([3, 3, 3, 4])

Docs:

maximum(x1, x2[, out])

Element-wise maximum of array elements.
Equivalent to np.where(x1 > x2, x1, x2) but faster and does proper broadcasting.

Upvotes: 42

jamylak
jamylak

Reputation: 133554

>>> import numpy as np
>>> a = np.array([1,2,3,4])
>>> n = 3
>>> a[a<n] = n
>>> a
array([3, 3, 3, 4])

Upvotes: 4

Related Questions