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
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
[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
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
[ 4 9 16 25]
[2. 3. 4. 5.]
[1.2 5.7]
Function | What it does |
|---|---|
| Add or subtract element by element (same as + and -) |
| Multiply or divide element by element (same as * and /) |
| Raise to a power (same as **) |
| Square root, absolute value |
| Round to a number of decimals |
| Exponential and natural logarithm |
Add up values
Example
import numpy as np
arr = np.array([1, 2, 3, 4])
print(np.sum(arr))
print(np.prod(arr))
print(np.cumsum(arr))
Output
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
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
29
[ 7 10 12]
[16 13]