Element by element
import numpy as np a = np.array([1, 2, 3, 4]) b = np.array([10, 20, 30, 40]) print(a + b) print(b - a) print(a * b) print(b / a)
Write Python. Understand every error.
NumPy · topic 20 of 25
Arithmetic between two arrays of the same shape works element by element: the first element with the first, the second with the second, and so on.
price = np.array([40, 25, 60]) qty = np.array([2, 4, 1]) print(price * qty) # [80 100 60]
An operation with a single number applies it to every element. NumPy also provides mathematical functions, called ufuncs, that work on whole arrays: np.sqrt, np.exp, np.log, np.abs, np.round(a, 2) and more.
Broadcasting lets NumPy combine arrays of different shapes by stretching the smaller one. Compare the shapes from the right-hand end. Each pair of sizes must be equal, or one of them must be 1.
(3, 4) with (4,) works: the row is added to every row(3, 4) with (3, 1) works: the column is added to every column(3, 4) with (3,) fails: 4 and 3 do not matchmarks = np.array([[60, 70, 80], [50, 90, 75]]) bonus = np.array([5, 0, 10]) # one bonus per subject print(marks + bonus)
When a column vector is needed, reshape(-1, 1) turns a 1D array into one column.
In-place operations such as a += 0.5 must keep the array's type. Adding a decimal to an integer array this way is an error; write a = a + 0.5 instead, which creates a new float array.
a + 10 adds 10 to every element and a * b multiplies matching elements.np.sqrt and np.exp also work on every element.* to be matrix multiplication. It multiplies matching elements, and @ is the matrix product.
import numpy as np a = np.array([1, 2, 3, 4]) b = np.array([10, 20, 30, 40]) print(a + b) print(b - a) print(a * b) print(b / a)
import numpy as np temps_c = np.array([20, 25, 30, 35]) temps_f = temps_c * 9 / 5 + 32 print(temps_f)
import numpy as np a = np.array([1, 4, 9, 16]) print(np.sqrt(a)) print(np.round(np.log(a), 2)) print(np.abs(np.array([-3, 2, -1])))
import numpy as np marks = np.array([[60, 70, 80], [50, 90, 75]]) bonus = np.array([5, 0, 10]) print(marks + bonus)
import numpy as np m = np.arange(6).reshape(2, 3) col = np.array([100, 200]).reshape(-1, 1) print(m + col)
import numpy as np a = np.array([1, 2, 3]) b = np.array([1, 2]) print(a + b) # run this to see the explanation
5 quick questions to check your understanding. Choose an answer for each, then press Check answers.
import numpy as np a = np.array([1, 2, 3]) print(a + 10)
Broadcasting adds the single number to every element.
import numpy as np a = np.array([1, 4, 9]) print(np.sqrt(a))
np.sqrt works on every element and gives floats.
import numpy as np a = np.array([[1, 2], [3, 4]]) print(a * a)
* multiplies matching elements. It is not matrix multiplication.
import numpy as np a = np.array([2, 4, 6]) b = np.array([1, 2, 3]) print(a / b)
Division gives floats, element by element.
Broadcasting lets you combine arrays of different but compatible shapes.