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?
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 tonp.where(x1 > x2, x1, x2)
but faster and does proper broadcasting.
>>> import numpy as np >>> a = np.array([1,2,3,4]) >>> n = 3 >>> a[a<n] = n >>> a array([3, 3, 3, 4])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With