Subtract arrays without explicit Python loops
Vectorized numerical computation
NumPy · Function
Subtracts two operands element by element, following NumPy broadcasting rules. It returns an ndarray for array inputs and a scalar when both inputs are scalars.
np.subtract is a universal function that computes x1 minus x2 element by element. Its inputs can be scalars or array-like values; when their shapes differ but are broadcast-compatible, NumPy aligns them before subtraction and produces an array or scalar result.
numpy.subtract(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True [, signature])| Name | Type | Description |
|---|---|---|
x1 | array_like | First input operand. |
x2 | array_like | Second input operand. |
out | ndarray, None, or tuple of ndarray and None | A location into which the result is written. |
where | array_like | Condition selecting locations where the result is calculated. |
casting | {'no','equiv','safe','same_kind','unsafe'} | Controls the permitted data-type casting behavior. |
order | {'K','C','F','A'} | Memory layout order for the output. |
dtype | dtype | Data type used for the result. |
subok | bool | Whether subclasses of ndarray are preserved. |
signature | string or tuple of ints | Generalized ufunc signature, when applicable. |
An ndarray containing x1 - x2 element-wise, or a scalar when both inputs are scalars.
import numpy as np
values = np.arange(9.0).reshape(3, 3)
offsets = np.arange(3.0)
result = np.subtract(values, offsets)
print(result)
# [[0. 0. 0.]
# [3. 3. 3.]
# [6. 6. 6.]]Subtracts each column offset from the corresponding row elements using broadcasting.
Vectorized numerical computation
Broadcasted adjustment
Memory-conscious pipelines
np.subtract computes the difference of x1 and x2 element-wise. If both inputs are scalars, the result is a scalar; otherwise, the result is an ndarray.
Follow-up: How can differently shaped inputs work? They must be compatible under NumPy broadcasting, which aligns dimensions before subtraction.
The function accepts two positional operands, x1 and x2, followed by keyword-only controls such as out, where, casting, order, dtype, and subok. The signature identifies it as a NumPy ufunc.
Follow-up: Why use out? It lets the computation write into a supplied output array, avoiding allocation when an appropriate destination is available.
For example, a 3-by-3 array and a length-3 array produce a 3-by-3 result because the smaller operand broadcasts across rows. Each output element is the corresponding value from x1 minus x2.
Follow-up: What must be true for broadcasting to succeed? The operands' dimensions must satisfy NumPy's broadcasting compatibility rules; incompatible shapes raise an error.
numpy.addnumpy.multiplynumpy.dividenumpy.remaindernumpy.true_divide