'Numpy vectorize excluded argument

Please I need someone to explain the function of excluded argument in Numpy vectorize function in a simple way.



Solution 1:[1]

Sometimes you don't want all of your objects to be iterated. Two examples:

in your function f(a,b) is for single elements like np.mod(a,b). No problem vectorizing here:

import numpy as np

vc = np.vectorize(np.mod)
print(vc([5,11,7,4],2)) # first element will be iterated
print(vc([5,11,7,4],[2,3,4,5])) # both elements will be iterated
print(vc(5,[2,3,4,5])) # only second element will be iterated

on the other hand you have a function g(x,p) which requires an array for p (example: a lookup table or parameters for a polynom). Therefore p has to stay an array, otherwhise the function would give an error or false data. This is done by excluding p. Please note that by using exclude, all your parameters now have to be named. Example:

import numpy as np

def g(x,p):
  return p[0]+x*p[1]+x*x*p[2]

print(g(5,[0,0,1]))

vg = np.vectorize(g, excluded=['p'])
print(vg(x=[0,1,2,3,4,5],p=[0,0,1])) # p will not be iterated

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1