What Is a NumPy ufunc?

A NumPy ufunc (Universal Function) is a function that performs element-wise operations on NumPy arrays. ufuncs are designed to be fast, memory-efficient, and vectorized, meaning they operate on entire arrays without using explicit Python loops.

ufuncs are implemented in C, which makes them significantly faster than standard Python operations.

Why Use NumPy ufuncs?

NumPy ufuncs are preferred because they:

  • Work element by element on arrays

  • Are much faster than Python loops

  • Support broadcasting

  • Handle large datasets efficiently

  • Produce clean and readable code

Simple Example (Without ufunc)

Python
a = [1, 2, 3] result = [] for i in a: result.append(i + 2) print(result) # Output: # [3, 4, 5]

Same Example Using NumPy ufunc

Python
import numpy as np a = np.array([1, 2, 3]) result = np.add(a, 2) print(result) # Output: # [3 4 5]

Here, np.add() is a ufunc that adds 2 to every element in the array.

Common NumPy ufuncs

Arithmetic ufuncs

Python
import numpy as np a = np.array([10, 20, 30]) b = np.array([1, 2, 3]) print(np.add(a, b)) print(np.subtract(a, b)) print(np.multiply(a, b)) print(np.divide(a, b)) # Output: # [11 22 33] # [ 9 18 27] # [10 40 90] # [10. 10. 10.]

Power and Modulus

Python
a = np.array([2, 3, 4]) print(np.power(a, 2)) print(np.mod(a, 2)) # Output: # [ 4 9 16] # [0 1 0]

Trigonometric ufuncs

Python
angles = np.array([0, np.pi/2, np.pi]) print(np.sin(angles)) print(np.cos(angles)) # Output: # [0.000000e+00 1.000000e+00 1.224647e-16] # [ 1.000000e+00 6.123234e-17 -1.000000e+00]

Comparison ufuncs

Python
a = np.array([10, 20, 30]) print(np.greater(a, 15)) print(np.equal(a, 20)) # Output: # [False True True] # [False True False]

These return Boolean arrays, useful in filtering and conditions.

Math ufuncs

Python
a = np.array([1.2, 2.5, 3.7]) print(np.floor(a)) print(np.ceil(a)) print(np.sqrt(a)) # Output: # [1. 2. 3.] # [2. 3. 4.] 

ufuncs and Broadcasting

ufuncs support broadcasting, meaning they can operate on arrays of different shapes.

Python
a = np.array([1, 2, 3]) b = 10 print(np.add(a, b)) # Output: # [11 12 13]

Here, b is automatically applied to every element in a.

Key Characteristics of ufuncs

  • Operate element-wise

  • Faster than Python loops

  • Support multiple inputs

  • Return NumPy arrays

  • Can handle missing values (NaN)