Array arithmetic
Combine vectors, matrices, or other numeric arrays position by position.
NumPy · Function
Adds two inputs element by element. Compatible shapes are broadcast, and the result is an array or scalar depending on the inputs.
np.add is a universal function that computes the element-wise sum of two inputs. NumPy broadcasts compatible shapes, applies the selected type and output rules, and returns either an array or a scalar.
numpy.add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True [, signature])| Name | Type | Description |
|---|---|---|
x1 | array_like | The first array-like operand. |
x2 | array_like | The second array-like operand. |
out | ndarray or None | A location into which the result is written. |
where | array_like of bool or bool | Boolean condition selecting output positions. |
casting | {'no','equiv','safe','same_kind','unsafe'}, optional | Controls permitted input-to-output casting. |
order | {'K','A','C','F'}, optional | Memory layout order for the result. |
dtype | dtype, optional | Output data type. |
subok | bool, optional | Whether subclasses are propagated. |
signature | string or tuple of ints, optional | Generalized-ufunc signature when applicable. |
add: ndarray or scalar — the element-wise sum; a scalar when both inputs are scalars.
x1 and x2 are the two array-like operands.import numpy as np
values = np.array([[1, 2, 3], [4, 5, 6]])
offset = np.array([10, 20, 30])
result = np.add(values, offset)
print(result)
Adds the one-dimensional offset to each row through broadcasting.
Combine vectors, matrices, or other numeric arrays position by position.
Add a shared row- or column-shaped offset to a larger array.
Write sums into an existing buffer when controlling allocation matters.
np.add do?np.add is a ufunc that adds two inputs element by element. It supports broadcasting, so compatible unequal shapes are expanded conceptually to a common shape.
Follow-up: How would you add an array to every row of a matrix? Pass a one-dimensional array whose length matches the matrix's column dimension; broadcasting aligns it with each row.
np.add return?The result is an ndarray for array inputs or a scalar when both inputs are scalars. Its values are the element-wise sums of the two operands.
Follow-up: What determines the array's shape? Broadcasting determines a common output shape from the input shapes.
out can receive the computed result, while where controls which positions are evaluated or assigned. The function also exposes casting, ordering, dtype, and subclass-related options.
Follow-up: Why use out? It permits writing into a supplied output array, which can avoid allocating another result when the supplied array is suitable.
numpy.ufuncnumpy.add.atnumpy.add.reducenumpy.add.accumulatenumpy.add.reduceat