Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 736
petrichor Avatar asked May 16 '13 12:05

petrichor


2 Answers

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.

like image 89
askewchan Avatar answered Oct 21 '22 04:10

askewchan


>>> import numpy as np >>> a = np.array([1,2,3,4]) >>> n = 3 >>> a[a<n] = n >>> a array([3, 3, 3, 4]) 
like image 27
jamylak Avatar answered Oct 21 '22 05:10

jamylak