To create your own ufunc, first define a function just like a regular Python function, then add it to the NumPy ufunc library using the frompyfunc()
method.
The frompyfunc()
method requires three arguments:
Create your own ufunc for addition:
import numpy as np def myadd(x, y): return x+y myadd = np.frompyfunc(myadd, 2, 1) print(myadd([1, 2, 3, 4], [5, 6, 7, 8])) |
To determine whether a function is a ufunc, check its type. A ufunc will return <class ‘numpy.ufunc’>.
Verify whether a function is a ufunc:
import numpy as np print(type(np.add)) |
If it is not a ufunc, it will return a different type, such as this built-in NumPy function for concatenating two or more arrays:
Verify the type of another function: concatenate():
import numpy as np print(type(np.concatenate)) |
If the function is not recognized, it will produce an error:
Check the type of a non-existent object. This will result in an error:
import numpy as np print(type(np.blahblah)) |
To determine if a function is a ufunc within an if statement, use the numpy.ufunc value (or np.ufunc if you have imported NumPy as np):
Utilize an if statement to determine whether the function is a ufunc:
import numpy as np if type(np.add) == np.ufunc: print(‘add is ufunc’) else: print(‘add is not ufunc’) |