LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.
Python Data Science NumPy ufunc Creating Your Own ufunc
How To Create Your Own ufunc?
In order to create you own ufunc, you have to define a function, like you do with normal functions
in Python, then you add it to your NumPy ufunc library with the frompyfunc() method.
The frompyfunc() method takes the following arguments.
1. function - the name of the function.
2. inputs - the number of input arguments (arrays).
3. outputs - the number of output arrays.
Example 1: Create your own ufunc for addition.
Code
import numpy as np
def myadd(x, y): return x+ymyadd = np.frompyfunc(myadd, 2, 1)
print(myadd([11, 12, 13, 14], [15, 16, 17, 18]))
the output will be
[26 28 30 32]
How to Check if a Function is a ufunc?
In order to Check the type of a function to check if it is a ufunc or not.
A ufunc should return <class 'numpy.ufunc'>.
Example 2: Check if a function is a ufunc.
Code
import numpy as np
print(type(np.add))
the output will be
<class 'numpy.ufunc'>
If it is not a ufunc, it will return another type, like this built-in NumPy function for
joining two or more arrays
Example 3: Check the type of another function concatenate().
Code
import numpy as np
print(type(np.concatenate))
the output will be
<class 'builtin_function_or_method'>
If the function is not recognized at all, it will return an error.
Example 4: Check the type of something that does not exist. This will produce an error.
Code
import numpy as np
print(type(np.something))
the output will be
AttributeError: module 'numpy' has no attribute 'something'
To test if the function is a ufunc in an if statement, use the numpy.ufunc
value (or np.ufunc if you use np as an alias for numpy)
Example 5: Use an if statement to check if the function is a ufunc or not.
Code
import numpy as np if type(np.add) == np.ufunc: print('add is ufunc') else: print('add is not ufunc')the output will be
add is ufunc
Note: NumPy ufunc Universal function or ufuncs is a function which operates on ndarrays in an element by element fashion and supports array broadcasting, type casting, and many other standard features.