NumPy - Array Subtraction
NumPy Array Subtraction
NumPy array subtraction allows you to perform element-wise subtraction between arrays. This operation subtracts corresponding elements of one array from another array of the same shape, producing a new array of the same shape with the subtracted 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 Subtraction in NumPy
Element-wise subtraction is the most basic form of array subtraction in NumPy, where corresponding elements of two arrays are subtracted to produce a new array.
This type of subtraction operates on arrays of the same shape, performing the subtraction operation individually for each pair of elements from the two arrays.
Example
In the following example, we are subtracting each element of array a from the corresponding element of array a −
import numpy as np
# Creating two arrays
a = np.array([5, 6, 7])
b = np.array([1, 2, 3])
# Performing element-wise subtraction
result = a - b
print(result)
Following is the output obtained −
[4 4 4]
Subtracting a Scalar to a NumPy Array
When a scalar (a single value) is subtracted from 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 explains how NumPy manages arithmetic operations involving arrays of different shapes. When arrays with varying shapes are used in calculations, NumPy automatically adjusts their shapes to be compatible with each other according to the broadcasting rules.
Example
In this example, we are subtracting the scalar “10” from each element of the array “a” −
import numpy as np
# Creating an array
a = np.array([5, 6, 7])
# Subtracting a scalar
result = a - 2
print(result)
This will produce the following result −
[3 4 5]
Subtracting NumPy Arrays of Different Shapes
Broadcasting in NumPy allows for the subtraction of arrays with different shapes by adjusting their dimensions to match each other.
NumPy aligns dimensions for broadcasting by comparing from the rightmost side and moving leftward. Dimensions are compatible if they are equal or if one dimension is 1, which is then expanded to match the other dimension.
When dimensions do not align directly, NumPy extends the smaller array along the mismatched dimensions as needed to fit 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 subtraction is performed −
import numpy as np
# Creating arrays with different shapes
a = np.array([[5, 6, 7], [8, 9, 10]])
b = np.array([1, 2, 3])
# Subtracting arrays with broadcasting
result = a - b
print(result)
Following is the output of the above code −
[[4 4 4]
[7 7 7]]
Subtracting Multi-Dimensional Arrays with Broadcasting
In NumPy, broadcasting allows for arithmetic operations, such as subtraction, between multi-dimensional arrays of different shapes by automatically expanding the dimensions of the smaller array to match the shape of the larger array.
Example
In the example below, we broadcast the one-dimensional array “b” to match the dimensions of the two-dimensional array “a” −
import numpy as np
# Creating multi-dimensional arrays
a = np.array([[10, 20, 30], [40, 50, 60]])
b = np.array([5, 15, 25])
# Subtracting multi-dimensional arrays with broadcasting
result = a - b[np.newaxis, :]
print(result)
The output obtained is as shown below −
[[ 5 15 25]
[25 35 45]]
Subtracting By Applying Functions with Broadcasting
Broadcasting in NumPy not only allows for direct element-wise arithmetic operations but also facilitates applying functions to arrays with different shapes. With broadcasting, you can use various mathematical functions on arrays of different shapes.
Example
In this example, we are subtracting the scalar “5” from each element of the array “a”, and then apply the “sine” function element-wise −
import numpy as np
# Creating an array
a = np.array([10, 20, 30])
# Applying a function with broadcasting
result = np.sin(a - 5)
print(result)
After executing the above code, we get the following output −
[-0.95892427 -0.7568025 0.14112001]
Subtracting Incompatible Arrays
If we attempt to subtract 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.
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([10, 20, 30])
b = np.array([[1, 2], [3, 4]])
# Subtracting 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)