Assigning Numbered Objects Using Boolean Operators

I would like to assign a function with a boolean estimate in it using a quick method. Here is a simple example. I want the following function to be evaluated for arbitrary aand b:

a = 0.5
b = 0.6
def func(x):
    x=max(x,a)
    if x>b:
        return x**2
    else:
        return x**3

and then I want to assign the values ​​of the functions in the array in a vectorized way (for speed):

xRange = np.arange(0, 1, 0.1)
arr_func = func(xRange)

But I get the error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any () or a.all ()

Now I know that I can assign values ​​in a loop. But it will be slow compared to the vectorized equivalent. Is it possible to get around this exception and still assign values ​​in vector form?

+4
3

, np.where:

def func(x):
    x = np.where(a > x, a, x)
    return np.where(x > b, x**2, x**3)
+4

np.select - , ,

def func(x):
    condlist =   [
                  x < a, 
                  (x >= a) & (x <= b), 
                  x > b
                 ]
    choicelist = [
                  a**3, 
                  x**3, 
                  x**2
                 ]
    return np.select(condlist, choicelist)

def func(x):
    condlist =   [
                  x < a,  
                  x > b
                 ]
    choicelist = [
                  a**3, 
                  x**2
                 ]
    return np.select(condlist, choicelist, default = x**3)
+2

( ) , numpy , "" , numpy .

, , for. , "" !

import numpy as np

def func(x, a=0.5, b=0.6):
    x = max(x, a)
    if x > b:
        return x**2
    else:
        return x**3

vfunc = np.vectorize(func)  # this is it!

xRange = np.arange(0, 1, 0.1)
arr_func = vfunc(xRange)

print(arr_func)

:

[ 0.125  0.125  0.125  0.125  0.125  0.125  0.36   0.49   0.64   0.81 ]
0

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


All Articles