ufunc (Universal Function) (NumPy)
A ufunc is a NumPy function that operates element-wise on whole arrays in fast compiled code — examples include np.sqrt, np.exp, np.add, and np.sin. Ufuncs are how NumPy applies math across an array without a Python loop.
NumPy
Universal functions take one or more arrays and apply the same operation to every corresponding element, returning a new array of results. Arithmetic operators like + and * are really shorthand for ufuncs (np.add, np.multiply), and they support broadcasting so differently shaped inputs combine cleanly.
Because the loop runs in C, a ufunc over a million-element array is dramatically faster than the equivalent Python for-loop. Ufuncs also accept an out argument to write results into an existing array (saving allocation) and offer reduction methods like np.add.reduce.
Math functions you import as np.<name> are almost all ufuncs; reaching for them instead of looping is the essence of writing fast, idiomatic NumPy.
Syntax
np.sqrt(a) | np.add(a, b) | a + bExamples
Python
import numpy as np
print(np.sqrt(np.array([1, 4, 9])))Output:
[1. 2. 3.]