numpy.vectorize#
- classnumpy.vectorize(pyfunc=np._NoValue,otypes=None,doc=None,excluded=None,cache=False,signature=None)[source]#
Returns an object that acts like pyfunc, but takes arrays as input.
Define a vectorized function which takes a nested sequence of objects ornumpy arrays as inputs and returns a single numpy array or a tuple of numpyarrays. The vectorized function evaluatespyfunc over successive tuplesof the input arrays like the python map function, except it uses thebroadcasting rules of numpy.
The data type of the output ofvectorized is determined by callingthe function with the first element of the input. This can be avoidedby specifying theotypes argument.
- Parameters:
- pyfunccallable, optional
A python function or method.Can be omitted to produce a decorator with keyword arguments.
- otypesstr or list of dtypes, optional
The output data type. It must be specified as either a string oftypecode characters or a list of data type specifiers. There shouldbe one data type specifier for each output.
- docstr, optional
The docstring for the function. If None, the docstring will be the
pyfunc.__doc__.- excludedset, optional
Set of strings or integers representing the positional or keywordarguments for which the function will not be vectorized. These will bepassed directly topyfunc unmodified.
- cachebool, optional
IfTrue, then cache the first function call that determines the numberof outputs ifotypes is not provided.
- signaturestring, optional
Generalized universal function signature, e.g.,
(m,n),(n)->(m)forvectorized matrix-vector multiplication. If provided,pyfuncwillbe called with (and expected to return) arrays with shapes given by thesize of corresponding core dimensions. By default,pyfuncisassumed to take scalars as input and output.
- Returns:
- outcallable
A vectorized function if
pyfuncwas provided,a decorator otherwise.
See also
frompyfuncTakes an arbitrary Python function and returns a ufunc
Notes
The
vectorizefunction is provided primarily for convenience, not forperformance. The implementation is essentially a for loop.Ifotypes is not specified, then a call to the function with thefirst argument will be used to determine the number of outputs. Theresults of this call will be cached ifcache isTrue to preventcalling the function twice. However, to implement the cache, theoriginal function must be wrapped which will slow down subsequentcalls, so only do this if your function is expensive.
The new keyword argument interface andexcluded argument supportfurther degrades performance.
References
Examples
>>>importnumpyasnp>>>defmyfunc(a,b):..."Return a-b if a>b, otherwise return a+b"...ifa>b:...returna-b...else:...returna+b
>>>vfunc=np.vectorize(myfunc)>>>vfunc([1,2,3,4],2)array([3, 4, 1, 2])
The docstring is taken from the input function to
vectorizeunless itis specified:>>>vfunc.__doc__'Return a-b if a>b, otherwise return a+b'>>>vfunc=np.vectorize(myfunc,doc='Vectorized `myfunc`')>>>vfunc.__doc__'Vectorized `myfunc`'
The output type is determined by evaluating the first element of the input,unless it is specified:
>>>out=vfunc([1,2,3,4],2)>>>type(out[0])<class 'numpy.int64'>>>>vfunc=np.vectorize(myfunc,otypes=[float])>>>out=vfunc([1,2,3,4],2)>>>type(out[0])<class 'numpy.float64'>
Theexcluded argument can be used to prevent vectorizing over certainarguments. This can be useful for array-like arguments of a fixed lengthsuch as the coefficients for a polynomial as in
polyval:>>>defmypolyval(p,x):..._p=list(p)...res=_p.pop(0)...while_p:...res=res*x+_p.pop(0)...returnres
Here, we exclude the zeroth argument from vectorization whether it ispassed by position or keyword.
>>>vpolyval=np.vectorize(mypolyval,excluded={0,'p'})>>>vpolyval([1,2,3],x=[0,1])array([3, 6])>>>vpolyval(p=[1,2,3],x=[0,1])array([3, 6])
Thesignature argument allows for vectorizing functions that act onnon-scalar arrays of fixed length. For example, you can use it for avectorized calculation of Pearson correlation coefficient and its p-value:
>>>importscipy.stats>>>pearsonr=np.vectorize(scipy.stats.pearsonr,...signature='(n),(n)->(),()')>>>pearsonr([[0,1,2,3]],[[1,2,3,4],[4,3,2,1]])(array([ 1., -1.]), array([ 0., 0.]))
Or for a vectorized convolution:
>>>convolve=np.vectorize(np.convolve,signature='(n),(m)->(k)')>>>convolve(np.eye(4),[1,2,1])array([[1., 2., 1., 0., 0., 0.], [0., 1., 2., 1., 0., 0.], [0., 0., 1., 2., 1., 0.], [0., 0., 0., 1., 2., 1.]])
Decorator syntax is supported. The decorator can be called asa function to provide keyword arguments:
>>>@np.vectorize...defidentity(x):...returnx...>>>identity([0,1,2])array([0, 1, 2])>>>@np.vectorize(otypes=[float])...defas_float(x):...returnx...>>>as_float([0,1,2])array([0., 1., 2.])
Methods
__call__(*args, **kwargs)Call self as a function.