Like np.add(), np.subtract(a, b) is the ufunc underlying the - operator, computing a minus b element-wise and following the same broadcasting rules for arrays of differing but compatible shapes. A common use is computing element-wise differences or distances, such as subtracting a mean array from a dataset to center it, or subtracting one array of coordinates from another to get displacement vectors.
1Understanding np.subtract()
Like np.add(), np.subtract(a, b) is the ufunc underlying the - operator, computing a minus b element-wise and following the same broadcasting rules for arrays of differing but compatible shapes. A common use is computing element-wise differences or distances, such as subtracting a mean array from a dataset to center it, or subtracting one array of coordinates from another to get displacement vectors.
Subtracting arrays of unsigned integer dtypes, like uint8, can silently wrap around to a huge positive number instead of going negative, since unsigned types can't represent negative values — cast to a signed type first if the subtraction result could be negative.
import numpy as np
a = np.array([10, 20, 30])
b = np.array([1, 2, 3])
print(np.subtract(a, b))2Practical Example
Here is a real-world application of np.subtract() showing how it is used in production NumPy code.
import numpy as np
data = np.array([[1, 2], [3, 4], [5, 6]])
mean = data.mean(axis=0)
centered = data - mean
print(centered)3Best Practices
Follow these guidelines when working with np.subtract():
1. Cast unsigned integer arrays to a signed dtype before subtracting if the result could be negative, to avoid silent integer wraparound
2. Use broadcasting, e.g. subtracting a 1D mean array from a 2D dataset, instead of looping row by row to center or normalize data
3. Use np.subtract(a, b, out=result_array) when you specifically want to write into a pre-allocated array instead of creating a new one
Tip: Subtracting arrays of unsigned integer dtypes, like uint8, can silently wrap around to a huge positive number instead of going negative, since unsigned types can't represent negative values — cast to a signed type first if the subtraction result could be negative.
import numpy as np
a = np.array([10, 20, 30])
b = np.array([1, 2, 3])
print(np.subtract(a, b))