Skip to content

NumPy Arithmetic Operations

Element-wise arithmetic

NumPy operations between arrays are usually element-wise.

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)
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)

Scalar operations

scalar
import numpy as np
 
arr = np.array([1, 2, 3])
print(arr * 10)
print(arr + 0.5)
scalar
import numpy as np
 
arr = np.array([1, 2, 3])
print(arr * 10)
print(arr + 0.5)

Power and modulo

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

Comparisons

Comparisons produce boolean arrays.

compare
import numpy as np
 
arr = np.array([10, 20, 30])
print(arr > 15)       # [False True True]
print(arr == 20)      # [False True False]
compare
import numpy as np
 
arr = np.array([10, 20, 30])
print(arr > 15)       # [False True True]
print(arr == 20)      # [False True False]

Aggregations (sum, mean, min, max)

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))
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

Element-wise multiplication

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

Matrix multiplication

Use @@ operator or np.matmulnp.matmul.

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

Rounding

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))
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))

Next

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

๐Ÿงช Try It Yourself

Exercise 1 โ€“ Create a NumPy Array

Exercise 2 โ€“ Array Shape and Reshape

Exercise 3 โ€“ Array Arithmetic

If this helped you, consider buying me a coffee โ˜•

Buy me a coffee

Was this page helpful?

Let us know how we did