Sub topic 6
Elementwise operations and universal functions
This chapter assumes you can create arrays and read their shape and dtype. It also assumes you know how indexing selects data. Here you will see how NumPy applies an operation to every element of an array at once.
Operators work elementwise
When two arrays have the same shape, an arithmetic operator combines the elements at matching positions. No loop is needed.
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(a * 2.5) # [ 2.5 5. 7.5 10. ]
print(a > 2) # [False False True True]a * b multiplies element by element. It is not a matrix product (that comes in a later chapter). A comparison such as a > 2 returns a boolean array, which you can later use as a mask.
In a * 2.5, the single number was applied to every element. This is the simplest case of broadcasting, which a later chapter covers fully.
What a universal function is
A universal function, or ufunc, is a NumPy function that operates on arrays elementwise. The operators above call ufuncs. a + b calls np.add(a, b), and a > 2 calls np.greater(a, 2). Ufuncs run in compiled code, so they are much faster than a Python for loop over the same data.
NumPy also provides named ufuncs for math and comparison:
import numpy as np
x = np.array([0.0, 1.0, 4.0, 9.0])
print(np.sqrt(x)) # [0. 1. 2. 3.]
p = np.array([1, 5, 3])
q = np.array([4, 2, 6])
print(np.maximum(p, q)) # [4 5 6]np.sqrt takes one input array. np.maximum takes two and returns the larger value at each position. Do not confuse it with np.max, which reduces a whole array to one value. Reductions are the next chapter's topic.
Result dtypes
The output dtype depends on the input dtypes. Mixing integers and floats gives floats. The / operator on integers always gives floats.
import numpy as np
a = np.array([1, 2, 3, 4])
print((a / 2).dtype) # float64
print((a // 2).dtype) # int64
small = np.array([100], dtype=np.int8)
print(small * 2) # [-56]The last line shows a common error. An int8 array holds values from -128 to 127. The result 200 does not fit, so it wraps around to -56. Array arithmetic gives no warning for integer overflow. If values may grow large, choose a wider dtype when you create the array.
Writing into an existing array
Ufuncs accept an out argument. It stores the result in an array you already have, which avoids allocating a new one.
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])
result = np.empty_like(a)
np.add(a, b, out=result)
print(result) # [11 22 33 44]The out array must have the right shape. Its dtype must also be able to hold the result without an unsafe conversion.
Key points
- Operators on same-shaped arrays act position by position.
- Operators are shorthand for ufuncs such as
np.addandnp.greater. - Ufuncs are fast because the loop runs in compiled code.
- Output dtype follows the inputs, and integer overflow wraps silently.
Exercise
What are the values and the dtype of np.array([1, 2, 3]) / 2? Why does the dtype differ from the input's?
Show answer
The result is [0.5 1. 1.5] with dtype float64. The / operator is true division, so it returns floats even when both inputs are integers.
Exercise
Given x = np.array([3, 8, 1]) and y = np.array([5, 2, 7]), which ufunc call returns [5 8 7], and why is np.max(x) not a substitute?
Show answer
np.maximum(x, y) returns [5 8 7] because it compares the arrays position by position. np.max(x) reduces one array to a single value (8), so it does not compare two arrays.