NumPy - Array Addition

NumPy Array Addition

NumPy array addition allows you to perform element-wise addition between arrays. This operation adds corresponding elements from two arrays of the same shape, producing a new array of the same shape with the summed values.

If the arrays have different shapes, NumPy can broadcast the smaller array to match the shape of the larger array under certain conditions.

Element-wise Addition in NumPy

Element-wise addition is the most basic form of array addition in NumPy, where corresponding elements of two arrays are added together to produce a new array.

This type of addition operates on arrays of the same shape, performing the addition operation individually for each pair of elements from the two arrays.

Example

In the following example, we are adding each element of array a is to the corresponding element of array b

import numpy as np

# Creating two arrays
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

# Performing element-wise addition
result = a + b
print(result)

Following is the output obtained −

[5 7 9]

Adding a Scalar to a NumPy Array

When a scalar (a single value) is added to an array, the scalar is broadcasted to match the shape of the array. This means that the scalar is effectively treated as if it were an array of the same shape as the original array, with all elements equal to the scalar value.

Broadcasting describes how NumPy handles arrays with different shapes during arithmetic operations. When arrays of different shapes are involved in operations, NumPy automatically adjusts their shapes to match each other, following specific broadcasting rules.

Example

In this example, we are adding the scalar “10” to each element of the array “a” −

import numpy as np

# Creating an array
a = np.array([1, 2, 3])

# Adding a scalar
result = a + 10
print(result)

This will produce the following result −

[11 12 13]

Adding NumPy Arrays of Different Shapes

Broadcasting in NumPy allows for the addition of arrays with different shapes by adjusting their dimensions to match each other.

NumPy aligns the dimensions of arrays for broadcasting by comparing dimensions from the rightmost side and working backward. Two dimensions are considered compatible if they are equal or if one of them is 1, in which case it is broadcasted to match the other dimension.

When dimensions do not directly match, NumPy stretches the smaller array along the mismatched dimensions as necessary to match the shape of the larger array.

Example

In the example below, array “b” is broadcasted to match the shape of array “a”, and then element-wise addition is performed −

import numpy as np

# Creating arrays with different shapes
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([10, 20, 30])

# Adding arrays with broadcasting
result = a + b
print(result)

Following is the output of the above code −

[[11 22 33]
 [14 25 36]]

Adding Multi-Dimensional Arrays with Broadcasting

In NumPy, broadcasting allows for arithmetic operations, such as addition, between multi-dimensional arrays of different shapes by automatically expanding the dimensions of the smaller array to match the larger array’s shape.

This process involves aligning dimensions from the rightmost side and stretching the smaller array’s dimensions as needed.

Example

In the example below, we broadcast the one-dimensional array “a” to match the dimensions of the two-dimensional array “b” −

import numpy as np

# Creating multi-dimensional arrays
a = np.array([1, 2, 3])
b = np.array([[10], [20], [30]])

# Adding multi-dimensional arrays with broadcasting
result = a + b
print(result)

The output obtained is as shown below −

[[11 12 13]
 [21 22 23]
 [31 32 33]]

Adding By Applying Functions with Broadcasting

Broadcasting in NumPy not only simplifies direct element-wise arithmetic operations but also allows for applying functions to arrays of different shapes. Using broadcasting, you can apply various mathematical functions across arrays with differing shapes.

Example

In this example, we are adding the scalar “10” to each element of the array “a”, and then apply the “sine” function element-wise −

import numpy as np

# Creating an array
a = np.array([1, 2, 3])

# Applying a function with broadcasting
result = np.sin(a + 10)
print(result)

After executing the above code, we get the following output −

[-0.99999021 -0.53657292  0.42016704]

Adding Incompatible Arrays

If we attempt to add incompatible arrays in NumPy, the operation will fail and raise a ValueError. NumPy uses broadcasting for operations between arrays of different shapes, but this is only possible if the shapes are compatible according to specific rules.

Broadcasting works by aligning the dimensions of the arrays starting from the rightmost dimension and working backward. For two dimensions to be compatible, they must either be equal or one of them must be 1 (in which case it is broadcasted to match the other dimension).

If the shapes of the arrays do not meet these criteria, broadcasting cannot occur, and the operation results in an error.

Example

In this case, the shapes of arrays “a” and “b” are not compatible for broadcasting, resulting in an error −

import numpy as np

# Creating arrays with incompatible shapes
a = np.array([1, 2, 3])
b = np.array([[10, 20], [30, 40]])

# Attempting to add incompatible arrays
result = a + b
print(result)

The result produced is as follows −

Traceback (most recent call last):File "/home/cg/root/66a1de2fae52f/main.py", line 8, in <module>result = a + bValueError: operands could not be broadcast together with shapes (3,) (2,2) 
© 2024 All rights reserved. | Made With 🤍 By The_MAK Team