NumPy Tutorial · NumPy ufunc

ufunc Create Function

Learn all about ufunc Create Function in this comprehensive tutorial.

5 min read advanced
  • To create your 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.
  • Check the type of a function to check if it is a ufunc or not.

How To Create Your Own ufunc

To create your 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:

  • function - the name of the function.
  • inputs - the number of input arguments (arrays).
  • outputs - the number of output arrays.
python

Check if a Function is a ufunc

Check the type of a function to check if it is a ufunc or not.

A ufunc should return <class 'numpy.ufunc'>.

python

If it is not a ufunc, it will return another type, like this built-in NumPy function for joining two or more arrays:

python

If the function is not recognized at all, it will return an error:

python

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):

python

Module quiz

2 questions
1

Which of the following is true about ufunc Create Function?

2

What is the most common pitfall when working with ufunc Create Function?

Answer all questions to submit.