NumPy add()
is a mathematical function and is used to calculate the addition between two NumPy arrays. You can perform array addition using the +
operator or the numpy.add()
function. The addition is performed element-wise, meaning each element in one array is added to the corresponding element in another array. The add()
function returns a scalar or nd-array. If the shapes of two arrays are not the same, that is arr.shape!=arr1.shape
, they must be broadcastable to a common shape.
In this article, I will explain the numpy.add()
function, covering its syntax, parameters, return value, and how to use it for array addition with examples.
1. Quick Examples of Array Addition
If you are in a hurry, below are some quick examples of NumPy array addition.
# Quick examples of array addition
# Example 1: Get addition values
# Using add() function
arr = [2, 4, 6, 8, 12, 14]
arr2 = np.add(arr, 12)
# Example 2: Use numpy.add() function
# To add two numbers
arr = np.array(12)
arr1 = np.array(25)
arr2 = np.add(arr, arr1)
# Example 3: Use numpy add() function
# With two input arrays
arr = np.array([2, 6, 9])
arr1 = np.array([5, 8, 12])
arr2 = np.add(arr, arr1)
# Example 4: Use numpy.ndarray.add() function
arr2 = arr.__add__(arr1)
# Example 5: Use + operator
arr2 = arr + arr1
# Example 6: Add numpy two multi-dimensional arrays
arr = np.array([[18, 25, 37], [5, -7, 15]])
arr1 = np.array([[4, 8, 12], [-13, 24, 17]])
arr2 = np.add(arr, arr1)
2. Syntax of NumPy add() Function
Following is the syntax of the numpy.add() function.
# Syntax of numpy.add()
numpy.add(arr, arr1, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) =
2.1 Parameters of add()
Following are the parameters of the add()
function.
arr
– The first input array or object works as an addition.arr1
– Second input array or object which works as an addition.out
– It is ndarray, None, or tuple of ndarray and None, optional. Out will be the location where the result is to be stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly allocated array is returned. A tuple must have a length equal to the number of outputs.where
(Optional) – A boolean array of the same shape asarr
andarr1
, whereTrue
indicates locations where the addition should be performed. The default isTrue
.**kwargs
– Allows passing keyword variable length of argument to a function. Used when we want to handle a named argument in a function.order
– {‘C’, ‘F’, ‘A’, ‘K’}, optional: ‘C’: means to flatten in row-major using C-style order. ‘F’: means to flatten in column-major (Fortran- style) order. ‘A’: means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. K’: means to flatten an in the order the elements occur in memory. By default, the ‘C’ index order is used.dtype
(Optional) – The data type of the output array. If not specified, the type is determined by the types ofarr
andarr1
.
2.2 Return Value
It returns nd-array. If both arr
and arr1
are scalars then it returns a scalar.
3. Usage of NumPy add() Function
The numpy.add()
is a mathematical function and is used to calculate the addition between two NumPy arrays. It will return the nd-array.
4. Add NumPy Array by scalar (Single Value)
You can add the array with a scalar value for that, you have to take an array named arr
and the scalar value is 12
then you will pass the array and scalar value as an argument in numpy.add()
function. It will return the nd-array.
In the below example, first, you import the NumPy library as np
. You create a 1D NumPy array arr
with values [2, 4, 6, 8, 12, 14]
. You use np.add()
it to add the scalar value 12
to each element of the array. You print the array arr2
, which contains the element-wise addition of arr
and 12
. So, the final array arr2
is [14,16,18,20,24,26]
, where each element is the sum of the corresponding element in the original array arr
and 12
.
# Import numpy
import numpy as np
# Creating an 1D input array
arr = [2, 4, 6, 8, 12, 14]
print("Original array:\n",arr)
# Using add() function
# Get addition values
arr2 = np.add(arr, 12)
print("Result of addition values:\n", arr2)
Yields below output.
5. Use numpy.add() Function to Add Two Numbers
The numpy.add()
function is designed for element-wise addition of arrays, but if you want to use it to add two individual numbers, you can create 0-dimensional NumPy arrays (scalars) and then use the function.
In the below example, arr
and arr1
are scalar NumPy arrays and np.add()
is used to perform the addition operation element-wise, resulting in the sum of the two numbers. The arr2
variable holds the final result, which is 37
in this case.
# Creating two numbers
arr = np.array(12)
arr1 = np.array(25)
# Use numpy.add() function to add two numbers
arr2 = np.add(arr, arr1)
print("Result of adding two numbers:",arr2)
Yields below output.
6. Use NumPy add() Function with Two Input Arrays
If you want to use the numpy.add()
function with two input arrays for element-wise addition. For instance, you create two 1D NumPy arrays, arr
and arr1
. You use np.add()
to add the corresponding elements of arr
and arr1
. The result is stored in arr2
. You print the array arr2
, which contains the element-wise addition of arr
and arr1
. So, the final array arr2
is [7, 14, 21]
, where each element is the sum of the corresponding elements in the original arrays arr
and arr1
.
# Create NumPy 2-D array
arr = np.array([2, 6, 9])
print("First array:", arr)
arr1 = np.array([5, 8, 12])
print("Second array:", arr1)
# Use numpy add() function
# With two input arrays
arr2 = np.add(arr, arr1)
print("Result of element-wise addition:",arr2)
# Output:
# First array: [2 6 9]
# Second array: [ 5 8 12]
# Result of element-wise addition: [ 7 14 21]
7. Use numpy.ndarray.add() Function
You can use numpy.ndarray.add()
function is used to add some value to every element of the array. You can use it to perform vector addition by passing the second array to this function.
# Use numpy.ndarray.add() function
arr2 = arr.__add__(arr1)
print(arr2)
Yields the same output as above.
8. Use + Operator
You can use the +
operator for element-wise addition of NumPy arrays. For example, the +
operator is used to add the corresponding elements of arr
and arr1
, resulting in the array [7, 14, 21]
. The +
operator is overloaded for NumPy arrays, allowing for intuitive element-wise operations.
# Use + operator
# For element-wise addition
arr2 = arr + arr1
print("Result of element-wise addition:",arr2)
Yields the same output as above.
9. Add NumPy Two Multi-Dimensional Arrays
When adding two multi-dimensional arrays in NumPy, the addition is performed element-wise. The arrays must have the same shape or be broadcastable to a common shape.
In the below example, the numpy.add()
function is used for element-wise addition of two 2D arrays (arr
and arr2
). The result is a new 2D array where each element is the sum of the corresponding elements in the original arrays.
# Create two multi-dimensional arrays
arr = np.array([[18, 25, 37], [5, -7, 15]])
print("First 2D array:\n", arr)
arr1 = np.array([[4, 8, 12], [-13, 24, 17]])
print("Second 2D array:\n", arr1)
# Add numpy two multi-dimensional arrays
arr2 = np.add(arr, arr1)
print("Result of element-wise addition of 2D arrays:\n",arr2)
# Output:
# First 2D array:
# [[18 25 37]
# [ 5 -7 15]]
# Second 2D array:
# [[ 4 8 12]
# [-13 24 17]]
# Result of element-wise addition of 2D arrays:
# [[22 33 49]
# [-8 17 32]]
Frequently Asked Questions
You can add two NumPy arrays element-wise using the numpy.add()
function or the +
operator. The arrays must have the same shape or be broadcastable to a common shape.
You can add a scalar value to a NumPy array. This operation will add the scalar value to each element of the array. You can use either the numpy.add()
function or the +
operator.
If the shapes of two arrays are not the same, NumPy will attempt to broadcast them to a common shape. If broadcasting is not possible, a ValueError
will be raised.
You can add two multi-dimensional arrays in NumPy using the numpy.add()
function or the +
operator. The arrays must have the same shape or be broadcastable to a common shape.
You can add two arrays of different shapes in NumPy if they are broadcastable to a common shape. Broadcasting rules will be applied to make the operation valid.
Conclusion
In this article, I have explained the syntax and usage of numpy.add()
function and used this function to calculate the addition of the NumPy array with examples.
Happy Learning!!
Related Articles
- NumPy flip() Function in Python
- How to Use NumPy argmax in Python
- How to Check NumPy Array Equal
- Cross Product in NumPy Python
- Python NumPy Absolute Value
- Python NumPy repeat() Function
- NumPy Inverse Matrix in Python
- NumPy Empty Array With Examples
- NumPy fill() Function with Examples
- How to Use NumPy pad() in Python
- NumPy full() Function with Examples
- NumPy Count Nonzero Values in Python