Comparing array elements with scalar and getting max in Python

I want to compare the elements of an array with a scalar and get an array with the maximum number of compared values. What 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 started

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

I get

 [1, 2, 3, 4] 

which is one of the two elements on the list, which is not the result I was aiming for. Is there a Numpy solution for fast, like other built-in functions?

+4
source share
2 answers

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

 a = np.arange(1,5) n = 3 np.maximum(a, n) #array([3, 3, 3, 4]) 

This does not mutate a :

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

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

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

Docs :

maximum(x1, x2[, out])

Elemental maximum of array elements.
Equivalent to np.where(x1 > x2, x1, x2) , but faster and does the right broadcast.

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

Source: https://habr.com/ru/post/1481173/


All Articles