Sub topic 8
Vectorized Arithmetic and Universal Functions
This chapter assumes you can create arrays and read their shape and dtype, and that you know the difference between a view and a copy. Broadcasting gets its own chapter, so here it appears only as a brief mention.
Why vectorize
A Python loop over an array runs the interpreter once per element. Each iteration looks up types, creates a Python object, and calls an operation. A vectorized expression hands the whole array to compiled C code. The C code loops over the typed memory block directly.
import numpy as np
prices = np.array([10.0, 20.0, 30.0])
qty = np.array([1, 2, 3])
# Loop version
total_loop = np.empty(3)
for i in range(3):
total_loop[i] = prices[i] * qty[i]
# Vectorized version
total = prices * qty
print(total) # [10. 40. 90.]
print(np.array_equal(total, total_loop)) # TrueOn arrays with millions of elements, the vectorized form is usually tens to hundreds of times faster. The code is also shorter.
What a universal function is
A universal function, or ufunc, is a function that applies an operation elementwise to arrays. Examples are np.add, np.sqrt, and np.exp. Ufuncs have three properties:
- They loop in compiled code, using a loop specialized for the input dtypes.
- They broadcast inputs of different shapes to a common shape.
- They accept optional arguments such as
out,where, anddtype.
The arithmetic operators are thin wrappers around ufuncs.
| Expression | Ufunc | Note |
|---|---|---|
| `a + b` | `np.add` | |
| `a - b` | `np.subtract` | |
| `a * b` | `np.multiply` | Elementwise, not matrix product |
| `a / b` | `np.true_divide` | Always returns floats |
| `a // b` | `np.floor_divide` | Rounds toward negative infinity |
| `a % b` | `np.remainder` | Sign follows the divisor |
| `a ** b` | `np.power` | |
| `-a` | `np.negative` | |
| `a > b` | `np.greater` | Returns a boolean array |
Ufuncs that take one array are unary, such as np.sqrt. Ufuncs that take two are binary, such as np.add and np.maximum.
Mixing dtypes
When the inputs have different dtypes, the ufunc picks a result dtype that can hold both. An int array plus a float array gives floats. Division with / always gives floats, even for integer inputs.
import numpy as np
a = np.array([1, 2, 3])
print(a / 2) # [0.5 1. 1.5]
print(a // 2) # [0 1 1]
print(np.array([-7]) // 2) # [-4], rounds toward negative infinity
print(np.array([-7]) % 2) # [1], sign follows the divisorFixed-width integers do not check for overflow in array arithmetic. The result wraps around silently.
import numpy as np
small = np.array([100, 120], dtype=np.int8)
print(small + 100) # [-56 -36], wrapped around, no error
print(small.astype(np.int16) + 100) # [200 220]Common mathematical ufuncs
NumPy provides ufuncs for most elementwise math. Use these instead of the math module, because math functions accept only scalars.
import numpy as np
x = np.array([4.0, 9.0, 16.0])
print(np.sqrt(x)) # [2. 3. 4.]
print(np.exp(np.array([0.0, 1.0]))) # [1. 2.71828183]
print(np.log(np.array([1.0, np.e]))) # [0. 1.]
print(np.abs(np.array([-3, 2]))) # [3 2]
print(np.sin(np.array([0.0, np.pi / 2]))) # [0. 1.]For two inputs, np.maximum and np.minimum compare elementwise. They differ from np.max and np.min, which reduce one array to a single value.
import numpy as np
print(np.maximum([1, 5, 3], [4, 2, 6])) # [4 5 6]
print(np.max([1, 5, 3])) # 5Floating-point edge cases
Float ufuncs follow IEEE 754 rules. Invalid operations produce nan and division by zero produces inf. NumPy also emits a RuntimeWarning, but the program keeps running.
import numpy as np
x = np.array([4.0, -1.0])
with np.errstate(invalid="ignore"):
print(np.sqrt(x)) # [ 2. nan]
with np.errstate(divide="ignore"):
print(1.0 / np.array([0.0, 2.0])) # [inf 0.5]np.errstate changes the warning behavior only inside the with block. Pass "raise" instead of "ignore" to turn the condition into an exception.
Remember that floats are approximate, so test closeness instead of equality.
import numpy as np
print(0.1 + 0.2 == 0.3) # False
print(np.isclose(0.1 + 0.2, 0.3)) # Truenp.isclose works on arrays and returns a boolean array. np.allclose returns a single boolean for the whole comparison.
Comparisons and logical combinations
Comparison operators are ufuncs that return boolean arrays. To combine them, use &, |, and ~. Wrap each comparison in parentheses, because & binds more tightly than > and <.
import numpy as np
a = np.array([1, 5, 8])
mask = (a > 2) & (a < 8)
print(mask) # [False True False]
print(~mask) # [ True False True]
try:
a > 2 and a < 8
except ValueError as err:
print("ValueError:", err)The Python keywords and and or ask for the truth value of a whole array, which is ambiguous. NumPy raises a ValueError instead of guessing.
Choosing between values with np.where
np.where(cond, x, y) picks from x where cond is true and from y elsewhere. It replaces an if inside a loop.
import numpy as np
a = np.array([3, -1, 4, -5])
print(np.where(a > 0, a, 0)) # [3 0 4 0]
print(np.where(a > 0, "pos", "neg")) # ['pos' 'neg' 'pos' 'neg']Both branches are evaluated for every element before selection. If one branch can produce a warning, such as np.log of a negative number, that warning still appears. Use the where argument of the ufunc, described next, to avoid computing those elements.
The out and where arguments
By default, each ufunc call allocates a new output array. The out argument writes the result into an array you supply. This avoids allocation and lets you update an array in place.
The where argument limits computation to elements where a mask is true. Elements outside the mask are left untouched in out, so you must initialize out yourself.
import numpy as np
x = np.array([4.0, -1.0, 9.0])
out = np.zeros_like(x)
np.sqrt(x, out=out, where=x >= 0)
print(out) # [2. 0. 3.]
a = np.array([1.0, 2.0, 3.0])
b = np.array([10.0, 20.0, 30.0])
np.add(a, b, out=a)
print(a) # [11. 22. 33.]If you omit out when using where, the skipped positions hold uninitialized memory, not zeros. Always supply out.
In-place operators and casting
The in-place operators +=, *=, and so on call the ufunc with out set to the left-hand array. The result must be castable back to that array's dtype under the same_kind rule. Writing floats into an integer array fails.
import numpy as np
n = np.array([1, 2, 3])
n += 2
print(n) # [3 4 5]
try:
n += 1.5
except TypeError as err:
print(type(err).__name__) # UFuncTypeError
n = n + 1.5 # creates a new float array
print(n) # [4.5 5.5 6.5]UFuncTypeError is a subclass of TypeError. The fix is either to create a new array with n = n + 1.5 or to start with a float array.
Ufunc methods
Binary ufuncs carry methods that generalize them. The most useful are reduce, accumulate, and outer.
import numpy as np
v = np.arange(5)
print(np.add.reduce(v)) # 10, same as v.sum()
print(np.add.accumulate(v)) # [ 0 1 3 6 10], running total
print(np.multiply.outer([1, 2, 3], [1, 2, 3]))
# [[1 2 3]
# [2 4 6]
# [3 6 9]]np.cumsum is the named shortcut for np.add.accumulate. outer applies the ufunc to every pair of elements from two inputs and builds a table of results.
Performance notes
Vectorizing is not automatically optimal. Keep these points in mind:
- Each operator in a long expression creates a temporary array.
a * b + callocates one temporary fora * b. For very large arrays,np.multiply(a, b, out=tmp)followed bytmp += cavoids that. - Calling a ufunc on a single scalar is slower than using
math. Vectorization pays off from roughly tens of elements upward. - Non-contiguous inputs, such as a transposed array or a strided slice, can run slower than contiguous ones.
np.vectorizedoes not make code fast. It is a convenience wrapper that still runs a Python loop internally.
To measure, use timeit on your own data instead of trusting general ratios.
import timeit
import numpy as np
x = np.random.default_rng(0).random(100_000)
loop = timeit.timeit(lambda: [v * 2 for v in x], number=5)
vec = timeit.timeit(lambda: x * 2, number=5)
print(f"loop {loop:.3f}s, vectorized {vec:.4f}s")Exercise
Given x = np.array([-2.0, 0.0, 3.0, 8.0]), write one expression that returns the square root of each element where x is at least 0, and 0.0 elsewhere, without emitting a RuntimeWarning. What is the result?
Show answer
out = np.zeros_like(x); np.sqrt(x, out=out, where=x >= 0). The result is [0. 0. 1.73205081 2.82842712]. The where mask skips the negative element, so sqrt is never computed for it and no warning is raised. Using np.where(x >= 0, np.sqrt(x), 0.0) gives the same values but still warns, because np.sqrt runs on every element first.
Exercise
Why does the following line raise an error, and how do you fix it? counts = np.array([1, 2, 3]); counts *= 0.5
Show answer
The in-place operator tries to store float64 results in an int64 array, which the same_kind casting rule forbids, so NumPy raises UFuncTypeError. Fix it by creating a new array, counts = counts * 0.5, or by starting with counts = np.array([1, 2, 3], dtype=float).