How does numpy.broadcast_to work with examples in Python
In this text, we will learn how the numpy.broadcast_to function works. Broadcasting is a method in numpy that allows us to do arithmetic operations on arrays of different sizes or shapes. We can perform arithmetic operations like addition or subtraction on arrays of equal sizes and shapes, but it is very difficult to perform arithmetic operations on two numpy arrays of different shapes and sizes. So, to overcome this problem we use the method of broadcasting.
- Broadcasting will stretch the value or array to the required shape and size.
- Then it will perform the arithmetic operation.
Now we will see how broadcasting in a numpy array is used to perform arithmetic operations of arrays of different sizes and shapes.
A few examples have been mentioned below.
Operations NumPy arrays:
In this example, we will see how to use the broadcasting to perform arithmetic operations on arrays of different sizes and shapes.
# Import the numpy module import numpy # create a numpy array array1=numpy.array([4,2,5,6,4]) # create another numpy array array2=numpy.array([1,5,6]) # shapes of both the arrays print("shape of array1: ",array1.shape) print("shape of array2: ",array2.shape)
Output:
shape of array1: (5,) shape of array2: (3,)
- This shows that both arrays are of different sizes. Array1 has 5 columns and array2 has got 3 columns. Now, if we try to directly perform arithmetic operations on both arrays, the compiler will throw an error.
- To prevent such errors, there are certain broadcasting rules.
Broadcasting rules:
- If the two arrays are of different dimensions then ones are padded on the left side of the array with fewer dimensions.
- If the shapes of the two numpy arrays are not equal then the arithmetic operations on those arrays cannot be performed. The operations can only be performed if the size of one of the arrays is 1.
# Import the numpy module import numpy # create a numpy array array1=numpy.array([[4,2],[3,6],[6,4]]) # create another numpy array array2=numpy.array([1,5]) print(array1+array2)
Output:
[[ 5 7] [ 4 11] [ 7 9]]
Broadcasting, is valid in this case according to the broadcasting rules.
Numpy.broadcast_to():
The numpy.broadcast_to() function is used to extend the number of rows and columns of numpy arrays of different sizes and shapes.
# Import the numpy module import numpy # create a numpy array array=numpy.array([1,7,3,4]) # use numpy.broadcast_to() c=numpy.broadcast_to(array,(4,4)) print(c)
Output:
Leave a Reply