32

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?

0

2 Answers 2

42

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Important note that can make you save 10 minutes : np.maximum is another function than np.max (which also exists!). It won't work with max, you have to use maximum :)
4
>>> import numpy as np
>>> a = np.array([1,2,3,4])
>>> n = 3
>>> a[a<n] = n
>>> a
array([3, 3, 3, 4])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.