TExcelTAD
Home › NumPy › ufunc Intro

NumPy ufunc Intro

A ufunc ("universal function") is a NumPy function that operates element by element on whole arrays. np.add, np.sqrt, np.sin, np.maximum and dozens more are ufuncs. They are written in C, so they run at compiled speed, and they are what makes NumPy code both short and fast.

Why ufuncs?

ufuncs give you vectorisation: an operation on a whole array instead of a Python loop over its elements. Compare adding two lists of numbers:

python · try it yourself
import numpy as np

a = [1, 2, 3, 4]
b = [10, 20, 30, 40]

# Pure Python: a loop (or zip + comprehension)
loop_result = []
for x, y in zip(a, b):
    loop_result.append(x + y)
print(loop_result)

# NumPy ufunc: one call, no loop
print(np.add(a, b))
[11, 22, 33, 44]
[11 22 33 44]

Note that np.add accepted plain lists; ufuncs convert their inputs to arrays automatically. The arithmetic operators on arrays (+, -, *, /, **, >…) are simply shortcuts for ufuncs: a + b calls np.add(a, b).

How much faster?

Let's time both approaches on a million numbers. (The exact times depend on your device, so we print only the ratio, rounded down to a rough category.)

python · try it yourself
import numpy as np
import time

n = 1_000_000
x = list(range(n))
y = list(range(n))

start = time.perf_counter()
z = [i + j for i, j in zip(x, y)]
loop_time = time.perf_counter() - start

xa, ya = np.array(x), np.array(y)
start = time.perf_counter()
za = np.add(xa, ya)
ufunc_time = time.perf_counter() - start

print("same result:", z[-1] == za[-1])
print("ufunc was more than 10x faster:", loop_time > 10 * ufunc_time)
same result: True
ufunc was more than 10x faster: True

On a typical computer the ufunc is 50 to 100 times faster, because the loop runs in C over raw numbers instead of creating a Python object for every element.

Common ufunc arguments

Every ufunc accepts some extra keyword arguments:

Argument Purpose
out write the result into an existing array (saves memory)
where a boolean mask: compute only where it is True
dtype the type of the result
python · try it yourself
import numpy as np

prices = np.array([10.0, 25.0, 40.0, 8.0])
taxed = np.empty_like(prices)
np.multiply(prices, 1.2, out=taxed)       # result goes into taxed
print(taxed)

# Only discount items over 20; others keep the value already in `out`
sale = prices.copy()
np.multiply(prices, 0.5, out=sale, where=prices > 20)
print(sale)

print(np.add([1, 2], [3, 4], dtype=np.float32))
[12.  30.  48.   9.6]
[10.  12.5 20.   8. ]
[4. 6.]

Is it a ufunc?

ufuncs have the type numpy.ufunc. Other NumPy functions (like np.concatenate or np.sort) are ordinary Python functions:

python · try it yourself
import numpy as np

for f in (np.add, np.sqrt, np.concatenate, np.sort):
    print(f"{f.__name__:12} is ufunc: {isinstance(f, np.ufunc)}")

print("inputs/outputs of np.add:", np.add.nin, np.add.nout)
add          is ufunc: True
sqrt         is ufunc: True
concatenate  is ufunc: False
sort         is ufunc: False
inputs/outputs of np.add: 2 1

nin and nout tell you how many inputs and outputs a ufunc has. np.add takes 2 inputs and produces 1 output (a binary ufunc); np.sqrt takes one (a unary ufunc).

Methods of ufuncs

Binary ufuncs come with handy methods, which you'll use in the Summations and Products lessons:

python · try it yourself
import numpy as np

a = np.array([2, 3, 4])
print(np.add.reduce(a))          # 2 + 3 + 4
print(np.add.accumulate(a))      # running totals
print(np.multiply.outer(a, a))   # multiplication table
9
[2 5 9]
[[ 4  6  8]
 [ 6  9 12]
 [ 8 12 16]]

Test yourself

What does 'ufunc' stand for?

  1. Unary function
  2. Universal function
  3. Unsigned function
  4. User function

Which ufunc does the expression a * b call for arrays?

  1. np.dot
  2. np.multiply
  3. np.prod
  4. np.matmul

What does the where argument of a ufunc do?

  1. Chooses the output file
  2. Limits the computation to positions where a mask is True
  3. Sorts the result
  4. Searches for a value