NumPy Array Math and ufuncs

Lesson 12 of 17

NumPy does arithmetic on whole arrays at once. The functions behind this are called ufuncs (universal functions) — they run element by element in fast compiled code.

Arithmetic between arrays

Example

Python
import numpy as np

a = np.array([10, 20, 30])
b = np.array([1, 2, 3])

print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a ** 2)

Output

Plain Text
[11 22 33]
[ 9 18 27]
[10 40 90]
[10. 10. 10.]
[100 400 900]

Each operator works element by element: the first value with the first, the second with the second, and so on.

Common ufuncs

Example

Python
import numpy as np

arr = np.array([-4, 9, -16, 25])

print(np.abs(arr))
print(np.sqrt(np.abs(arr)))
print(np.round(np.array([1.234, 5.678]), 1))

Output

Plain Text
[ 4  9 16 25]
[2. 3. 4. 5.]
[1.2 5.7]

Function

What it does

np.add(), np.subtract()

Add or subtract element by element (same as + and -)

np.multiply(), np.divide()

Multiply or divide element by element (same as * and /)

np.power()

Raise to a power (same as **)

np.sqrt(), np.abs()

Square root, absolute value

np.round()

Round to a number of decimals

np.exp(), np.log()

Exponential and natural logarithm

Add up values

Example

Python
import numpy as np

arr = np.array([1, 2, 3, 4])

print(np.sum(arr))
print(np.prod(arr))
print(np.cumsum(arr))

Output

Plain Text
10
24
[ 1  3  6 10]

Work along an axis

On a 2-D array, axis=0 works down the columns and axis=1 works across the rows:

Example

Python
import numpy as np

sales = np.array([[5, 3, 8],
                  [2, 7, 4]])

print(sales.sum())
print(sales.sum(axis=0))
print(sales.sum(axis=1))

Output

Plain Text
29
[ 7 10 12]
[16 13]