Create your own universal function in NumPy

Universal functions in Numpy are simple mathematical functions. It is just a term that we gave to mathematical functions in the Numpy library. Numpy provides various universal functions that cover a wide variety of operations. However, we can create our own universal function in Python. To create your own universal function in NumPy, we have to apply some steps given below:

  1. Define the function as usually using the def keyword.
  2. Add this function to numpy library using frompyfunc() method.
  3. Use this function using numpy.

frompyfunc() method

This function allows to create an arbitrary Python function as Numpy ufunc (universal function). This method takes the following arguments :


  • function – the name of the function that you create.
  • inputs – the number of input arguments (arrays) that function takes.
  • outputs – the number of output (arrays) that function produces.

Note: For more information, refer to numpy.frompyfunc() in Python.

Example :

  • Create function with name fxn that takes one value and also return one value.
  • The inputs are array elements one by one.
  • The outputs are modified array elements using some logic.






# using numpy
import numpy as np
# creating own function
def fxn(val):
  return (val % 2)
# adding into numpy
mod_2 = np.frompyfunc(fxn, 1, 1)
# creating nummpy array
arr = np.arange(1, 11)
print("arr     :", *arr)
# using function over nummpy array
mod_arr = mod_2(arr)
print("mod_arr :", *mod_arr)


Output :

arr     : 1 2 3 4 5 6 7 8 9 10
mod_arr : 1 0 1 0 1 0 1 0 1 0
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.