Sub topic 6
Elementwise operations and universal functions
This chapter assumes you can create arrays, read shape, ndim and dtype, and index and slice arrays. It also assumes you know basic Python functions and operators. Here you will learn how NumPy applies operations to whole arrays at once, what a universal function is, and which errors and surprises to expect.
The working model
An elementwise operation applies the same function to every element of an array, or to matching pairs of elements from two arrays. You write one expression, and NumPy runs the loop in compiled code.
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])
print(a + b) # [11 22 33 44]
print(a * b) # [ 10 40 90 160]
print(a ** 2) # [ 1 4 9 16]
print(b / a) # [10. 10. 10. 10.]The operators +, -, *, /, //, % and ** all work elementwise. In particular, * is not matrix multiplication. Matrix products use @, which a later chapter covers.
When both operands have the same shape, element i of the result comes from element i of each input. When the shapes differ, NumPy tries broadcasting, which a later chapter covers. For now, assume the two shapes are equal, or that one operand is a scalar.
import numpy as np
a = np.array([1, 2, 3])
print(a * 10) # [10 20 30]
print(a + 0.5) # [1.5 2.5 3.5]What a universal function is
A universal function, or ufunc, is a NumPy function that operates elementwise on arrays and supports broadcasting, type casting and optional output arguments. The operators above are shorthand for ufuncs. For example, a + b calls np.add(a, b).
Common ufuncs fall into a few groups:
| Group | Examples |
|---|---|
| Arithmetic | `np.add`, `np.subtract`, `np.multiply`, `np.divide`, `np.power`, `np.mod` |
| Math | `np.sqrt`, `np.exp`, `np.log`, `np.abs`, `np.sin`, `np.cos` |
| Comparison | `np.greater`, `np.less`, `np.equal`, `np.not_equal` |
| Logical | `np.logical_and`, `np.logical_or`, `np.logical_not` |
| Rounding | `np.floor`, `np.ceil`, `np.rint` |
Comparison operators such as > and == are also elementwise. They return a boolean array, not a single True or False.
import numpy as np
x = np.array([1.0, 4.0, 9.0, 16.0])
print(np.sqrt(x)) # [1. 2. 3. 4.]
print(np.exp([0, 1])) # [1. 2.71828183]
print(x > 5) # [False False True True]A ufunc accepts lists as well, since it converts them to arrays first. The result is always an ndarray.
Ufuncs on multidimensional arrays
Ufuncs do not care about the number of dimensions. They apply to every element, whatever the shape.
import numpy as np
m = np.arange(6).reshape(2, 3)
print(m * m)
# [[ 0 1 4]
# [ 9 16 25]]
print(np.sqrt(m).shape) # (2, 3)The result keeps the input shape. This is the defining property of an elementwise operation. A function that changes the shape, such as sum, is a reduction, which the next chapter covers.
Types and casting
Each array has one dtype. When a ufunc combines two arrays with different dtypes, NumPy picks a result dtype that can hold both. This is called type promotion.
import numpy as np
i = np.array([1, 2, 3]) # int64 on most platforms
f = np.array([0.5, 0.5, 0.5]) # float64
print((i + f).dtype) # float64
print((i / 2).dtype) # float64: true division always gives floats
print((i // 2).dtype) # int64: floor division keeps integersThree details matter in practice:
/always returns a floating-point result, even for integer inputs. Use//for integer floor division.- Small integer types can overflow. Adding two
uint8values above 255 wraps around instead of raising an error. - Mixing integers with floats produces floats, so a single stray float can change the dtype of a whole computation.
import numpy as np
u = np.array([200, 100], dtype=np.uint8)
print(u + u) # [144 200]The values wrap modulo 256. If you work with image data or other small integer types, convert to a wider type before arithmetic: u.astype(np.int32).
The out argument and in-place operators
Every ufunc creates a new array by default. For large arrays, this allocation costs memory and time. The out argument writes the result into an existing array.
import numpy as np
a = np.arange(5, dtype=np.float64)
b = np.ones(5)
result = np.empty(5)
np.add(a, b, out=result)
print(result) # [1. 2. 3. 4. 5.]The in-place operators +=, -=, *= and /= do the same for the left operand. They modify the existing array, so any view of that array sees the change.
import numpy as np
a = np.arange(4)
v = a[:2] # a view
a += 10
print(v) # [10 11]In-place operators have a casting rule. The result must be castable back to the dtype of the target array. This fails:
import numpy as np
a = np.arange(4) # integer dtype
try:
a /= 2
except TypeError as err:
print("error:", err)True division produces floats, and NumPy refuses to store them silently in an integer array. Write a = a / 2 instead, which creates a new float array.
Special values: nan and inf
Floating-point ufuncs follow IEEE 754 rules. Division by zero and invalid operations do not raise exceptions. They produce inf or nan and emit a RuntimeWarning.
import numpy as np
x = np.array([1.0, 0.0, -1.0])
with np.errstate(divide="ignore", invalid="ignore"):
print(1 / x) # [ inf inf -1.]
print(np.log(x)) # [ 0. -inf nan]
print(np.nan == np.nan) # Falsenp.errstate controls how NumPy reports these conditions. Use np.isnan and np.isinf to detect them, because nan == nan is False. Integer division by zero behaves differently. It returns 0 with a warning, rather than infinity.
Logical operators on arrays
Python's and, or and not do not work elementwise. They try to convert a whole array into one truth value, which raises an error for arrays with more than one element.
import numpy as np
a = np.arange(10)
try:
(a > 2) and (a < 7)
except ValueError as err:
print("error:", err)
mask = (a > 2) & (a < 7)
print(mask)
print(a[mask]) # [3 4 5 6]Use &, | and ~, and wrap each comparison in parentheses. Without parentheses, & binds tighter than >, and the expression means something different from what you intended. The functions np.logical_and, np.logical_or and np.logical_not do the same job.
Speed: why ufuncs are fast
A Python loop checks types and dispatches a function call for each element. A ufunc runs one compiled loop over a contiguous block of typed data. The gap is large for big arrays.
import numpy as np
import timeit
n = 1_000_000
a = np.arange(n, dtype=np.float64)
def python_loop():
return [x * 2.0 for x in a.tolist()]
def ufunc():
return a * 2.0
print("loop :", timeit.timeit(python_loop, number=5))
print("ufunc:", timeit.timeit(ufunc, number=5))Exact timings depend on your machine, but the ufunc is typically tens of times faster. A later chapter returns to vectorization and its memory cost.
Common errors
| Symptom | Likely cause | Fix | Column |
|---|---|---|---|
| `ValueError: truth value of an array is ambiguous` | Used `and`, `or` or an `if` on an array | Use `&`, ` | `, `~`, or `.any()` and `.all()` |
| `ValueError: operands could not be broadcast together` | Shapes are not equal or compatible | Check `.shape` of both operands | |
| Results too small or negative | Integer overflow in a small dtype | Use `astype` to a wider type | |
| `TypeError` on `/=` | In-place float result into an integer array | Create a new array instead | |
| `nan` spreading through results | A `nan` input or an invalid operation | Find it with `np.isnan` and handle it |
Summary
Operators and ufuncs apply a function to each element and keep the shape. Mixed dtypes are promoted, / always gives floats, and small integer types wrap on overflow. Use out or in-place operators to avoid temporary arrays, and use &, | and ~ for elementwise logic.
Exercise
Given a = np.array([250, 5], dtype=np.uint8), what does a + 10 return, and how do you get the mathematically correct result [260, 15]?
Show answer
With a Python integer scalar, current NumPy keeps the uint8 dtype, so 250 + 10 wraps to 4 and the result is [4 15]. Convert first with a.astype(np.int32) + 10, which gives [260 15]. Check .dtype to confirm the wider type.
Exercise
Why does (a > 2) and (a < 7) fail for an array a with ten elements, and what is the correct expression to keep the elements between 3 and 6 inclusive?
Show answer
Python's and needs a single truth value, but a boolean array with many elements has no unambiguous one, so NumPy raises a ValueError. Use a[(a > 2) & (a < 7)], with parentheses around each comparison.