Skip to content

NumPy Arithmetic Operations

NumPy operations between equal-size arrays apply the operation element-wise — this is what the book calls “vectorization,” and it’s what lets you skip writing for loops.

elementwise
import numpy as np
 
a = np.array([1, 2, 3])
b = np.array([10, 20, 30])
 
print(a + b)
print(a - b)
print(a * b)
print(a / b)

Arithmetic with a scalar propagates that value to every element in the array (this is broadcasting in its simplest form).

scalar
import numpy as np
 
arr = np.array([1, 2, 3])
print(arr * 10)
print(arr + 0.5)
power
import numpy as np
 
arr = np.array([2, 3, 4])
print(arr ** 2)  # [4 9 16]
print(arr % 2)   # [0 1 0]

Comparisons produce boolean arrays, applied element-wise just like arithmetic.

compare
import numpy as np
 
arr = np.array([10, 20, 30])
print(arr > 15)       # [False True True]
print(arr == 20)      # [False True False]
diagram Same array, four kinds of results mermaid
Arithmetic, comparison, and aggregation all start from the same element-wise machinery but end in different shapes.
agg
import numpy as np
 
mat = np.array([
    [1, 2, 3],
    [4, 5, 6]
])
 
print(mat.sum())          # sum of all
print(mat.sum(axis=0))    # column sums
print(mat.sum(axis=1))    # row sums
 
print(mat.mean(axis=0))
print(mat.min(axis=1))
print(mat.max(axis=1))

Matrix multiplication vs element-wise multiplication

Section titled “Matrix multiplication vs element-wise multiplication”

* multiplies matching positions — it is not the same as matrix multiplication.

mul
import numpy as np
 
a = np.array([[1, 2], [3, 4]])
b = np.array([[10, 20], [30, 40]])
print(a * b)

Use @ operator or np.matmul.

matmul
import numpy as np
 
a = np.array([[1, 2], [3, 4]])
b = np.array([[10, 20], [30, 40]])
print(a @ b)
rounding
import numpy as np
 
arr = np.array([1.234, 5.678])
print(np.round(arr, 2))
print(np.floor(arr))
print(np.ceil(arr))

Continue to: NumPy Universal Functions (ufuncs) to learn fast built-in vectorized functions.

Exercise 1 – Element-wise vs Matrix Multiplication

Section titled “Exercise 1 – Element-wise vs Matrix Multiplication”

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading