Home > Back-end >  Is there any way to apply a function to an array of lists in pyhton?
Is there any way to apply a function to an array of lists in pyhton?

Time:04-17

I have an array of lists of two coordinates. I want to apply this function:

def f(x, y, a, b):
return sign(y - a*x - b)

in which x and y are the coordinates, a and b defines the line equation.

The function returns the sign of the distance between the line and the point.

Is there any way to apply this function to an array of list at once and obtain the label list? like:

Y = f(x[:,0],x[:,1],a,b)

Thanks

CodePudding user response:

you can use numpy vectorize :

vectorize define a vectorized function which takes a nested sequence of objects or numpy arrays as inputs and returns a single numpy array or a tuple of numpy arrays. The vectorized function evaluates pyfunc over successive tuples of the input arrays like the python map function, except it uses the broadcasting rules of numpy.

read more about numpy.vectorize here

def f(x, y, a, b):
    return np.sign(y - a*x - b)
vfunc = np.vectorize(f)

output :

x = np.random.rand(10,10)
y = np.random.rand(10,10)
Y = vfunc(x[:,0],y[:,1],1,0)
print(Y)

>> [-1.  1.  1. -1. -1. -1. -1.  1. -1. -1.]

CodePudding user response:

you mean map(), map call function for every element of iterable

for example:

def f(x):
  return x**2

lst = [1,2,3,4,5]

print(tuple(map(f, lst)))

Output:

(1,4,9,16,25)

*Very important map return generator, so you need to use tuple() or list() to get values from map

  • Related