Curriculum
Course: NumPy
Login

Curriculum

NumPy

Text lesson

ufunc Create Function

How To Create Your Own ufunc

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:

  • function: The name of the function to be converted.
  • inputs: The number of input arguments (arrays).
  • outputs: The number of output arrays.

Example

Create your own ufunc for addition:

import numpy as np

def myadd(x, y):
  return x+y

myadd = np.frompyfunc(myadd, 21)

print(myadd([1234], [5678]))

Check if a Function is a ufunc

To determine whether a function is a ufunc, check its type. A ufunc will return <class ‘numpy.ufunc’>.

Example

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:

Example

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:

Example

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

Example

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