Home > Blockchain >  apply max function to numpy.array
apply max function to numpy.array

Time:08-06

Good morning! I have an np.array (1.1,2.2,3.3), and i want to pass the array to a simple max function, max(0,(x-1.5)**3) and I expect return of an np.array (0,0.343,5.832) I tried the follow code and received error.

aaa = np.array([1.1, 2.2, 3.3])
max(0, (aaa-1.5)**3)

How can I get the expected result?

CodePudding user response:

Without using a list comprehension, therefore a for loop. You can apply your function with vectorization, create an array of zeros. Take the max of them :

import numpy as np

a = np.array((1.1,2.2,3.3))
b = np.zeros(len(a))
np.maximum((a-1.5)**3,b)

Output :

array([0.   , 0.343, 5.832])

CodePudding user response:

You should replace max() (which knows little about NumPy objects) with either numpy.maximum() or numpy.fmax(). Both work similarly: they compare two arrays element-wise outputing the maximum, broadcasting inputs with different shapes. They only differ in the way they treat NaNs: propagated with np.maximum() and ignored as much as possible with np.fmax().

In your example, the 0 gets broadcasted to the shape of aaa:

import numpy as np

aaa = np.array([1.1, 2.2, 3.3])
np.fmax(0, (aaa - 1.5) ** 3)
# array([0.   , 0.343, 5.832])

CodePudding user response:

x = np.array([1.1, 2.2, 3.3])
y = np.array(list(map(lambda t: max(0, (t - 1.5)**3), x)))
  • Related