ufunc Simple Arithmetic
NumPy has a ufunc for every arithmetic operation. You can call them by name or, more often, use the matching operator. Both take arrays, lists or scalars, and both work element by element.
| Operator | ufunc | Meaning |
|---|---|---|
a + b |
np.add(a, b) |
addition |
a - b |
np.subtract(a, b) |
subtraction |
a * b |
np.multiply(a, b) |
multiplication |
a / b |
np.divide(a, b) |
true division (always float) |
a // b |
np.floor_divide(a, b) |
floor division |
a ** b |
np.power(a, b) |
power |
a % b |
np.mod(a, b) / np.remainder |
remainder |
-a |
np.negative(a) |
negation |
abs(a) |
np.absolute(a) / np.abs |
absolute value |
Add, subtract, multiply, divide
import numpy as np
income = np.array([3200, 2800, 4100])
expenses = np.array([2100, 2950, 3000])
print(np.add(income, expenses))
print(np.subtract(income, expenses)) # savings, can be negative
print(np.multiply(income, 12)) # yearly
print(np.divide(expenses, income).round(3)) # share spent[5300 5750 7100]
[1100 -150 1100]
[38400 33600 49200]
[0.656 1.054 0.732]
Power
np.power(a, b) raises each element of a to the matching power in b:
import numpy as np
base = np.array([2, 3, 4, 5])
exps = np.array([3, 2, 0, 1])
print(np.power(base, exps))
print(base ** 2)
# Compound interest: 1000 at 5 % for 0..4 years
years = np.arange(5)
print((1000 * np.power(1.05, years)).round(2))[8 9 1 5]
[ 4 9 16 25]
[1000. 1050. 1102.5 1157.63 1215.51]
Remainder and divmod
np.mod and np.remainder are the same function: the remainder after division. np.divmod returns the quotient and the remainder in one go, which is great for unit conversions:
import numpy as np
print(np.mod([10, 11, 12, 13], 4))
seconds = np.array([75, 3600, 4000, 59])
minutes, rest = np.divmod(seconds, 60)
for m, s in zip(minutes, rest):
print(f"{m} min {s:02d} s")[2 3 0 1]
1 min 15 s
60 min 00 s
66 min 40 s
0 min 59 s
With negative numbers, NumPy follows Python's rule: the remainder takes the sign of the divisor, so np.mod(-7, 3) is 2. If you want the C-style result with the sign of the dividend, use np.fmod(-7, 3), which is -1.
Absolute values
np.absolute and its short alias np.abs remove the sign. For complex numbers they return the magnitude:
import numpy as np
errors = np.array([-2.5, 0.0, 1.25, -0.75])
print(np.absolute(errors))
print("mean absolute error:", np.abs(errors).mean())
print(np.abs(np.array([3 + 4j, -1 + 0j])))[2.5 0. 1.25 0.75]
mean absolute error: 1.125
[5. 1.]
Dividing by zero
Dividing a float array by zero does not raise an exception. NumPy returns inf or nan and issues a warning. Use np.errstate to silence the warning when you expect it, then deal with the special values:
import numpy as np
hits = np.array([3.0, 0.0, 5.0])
tries = np.array([4.0, 0.0, 0.0])
with np.errstate(divide="ignore", invalid="ignore"):
rate = np.divide(hits, tries)
print(rate)
print(np.nan_to_num(rate, nan=0.0, posinf=0.0))
# or compute only where the divisor is nonzero
safe = np.divide(hits, tries, out=np.zeros_like(hits), where=tries != 0)
print(safe)[0.75 nan inf]
[0.75 0. 0. ]
[0.75 0. 0. ]
The last form, with out and where, is the cleanest: positions with a zero divisor are never computed and keep the value from out.
Test yourself
What does np.divmod(17, 5) return?
- (3, 2)
- 3.4
- (2, 3)
- 2
What is np.mod(-7, 3)?
- -1
- 1
- 2
- -2
What does np.array([1.0]) / 0 produce?
- A ZeroDivisionError
- [inf] with a RuntimeWarning
- [0.]
- [nan]