Sub topic 8
Vectorized arithmetic and universal functions
This chapter assumes you know what an ndarray is, how to read its shape and dtype, and how to create arrays with np.array and np.arange. Here you will replace Python loops with whole-array expressions.
What vectorization means
Vectorization means writing an operation once and letting NumPy apply it to every element. The loop still runs, but it runs in compiled C code over a typed block of memory. It does not run in the Python interpreter, which has to check types and create objects for each element.
import numpy as np
prices = np.array([10.0, 20.0, 30.0])
tax = prices * 0.2
total = prices + tax
print(total) # [12. 24. 36.]The expression prices * 0.2 has no loop. Arithmetic operators (+, -, *, /, //, %, **) work elementwise on arrays of the same shape. A scalar is applied to every element.
Universal functions
A universal function, or ufunc, is a NumPy function that operates elementwise on arrays. The operators above are shortcuts for ufuncs: + calls np.add, * calls np.multiply, and so on. Comparisons such as > are ufuncs that return boolean arrays.
import numpy as np
a = np.array([1.0, 4.0, 9.0])
b = np.array([3.0, 2.0, 10.0])
print(np.sqrt(a)) # [1. 2. 3.]
print(np.maximum(a, b)) # [ 3. 4. 10.]
print(a > b) # [False True False]Unary ufuncs take one array, such as np.sqrt, np.exp, np.log, and np.abs. Binary ufuncs take two, such as np.add, np.maximum, and np.power. Do not confuse np.maximum(a, b), which compares elementwise, with a.max(), which reduces one array to a single value.
Controlling the output
By default, every ufunc allocates a new result array. The out argument writes into an array you already have, which avoids the allocation in hot code.
import numpy as np
a = np.array([1.0, 4.0, 9.0])
b = np.array([3.0, 2.0, 10.0])
buf = np.empty(3)
np.add(a, b, out=buf)
print(buf) # [ 4. 6. 19.]
a += b # in-place: reuses a's memory
print(a) # [ 4. 6. 19.]In-place operators follow the dtype of the left-hand array. If a is an integer array, a += 0.5 raises an error because the float result cannot be safely cast back to integers.
Types and overflow
The result dtype comes from the input dtypes. Mixing int64 and float64 gives float64. Fixed-width integers do not raise on overflow. They wrap around silently.
import numpy as np
x = np.array([100, 120], dtype=np.int8)
print(x + x) # [-56 -16]The values 200 and 240 do not fit in int8, which holds -128 to 127. Choose a wider dtype, such as np.int64, when sums or products can grow large.
Common errors
- Writing a Python
forloop over an array and callingmath.sqrton each element. Usenp.sqrt(arr)instead.math.sqrtalso fails on whole arrays. - Using
andororon arrays. Use&and|, and put parentheses around each comparison, as in(a > 1) & (a < 5). - Expecting
a / bon integer arrays to give integers. True division always returns floats. Use//for floor division. - Dividing by zero. NumPy returns
infornanand emits a runtime warning. It does not raise an exception.
Exercise
Exercise
You have t = np.array([0.0, 50.0, 100.0]) of Celsius temperatures. Write one vectorized expression that converts them to Fahrenheit (F = C * 9/5 + 32). What does it return?
Show answer
t * 9 / 5 + 32 returns array([ 32., 122., 212.]). Each operator is a ufunc applied elementwise, so no loop is needed.