The broadcast mechanism in NumPy aims to solve the problem of arithmetic operation between arrays of different shapes.
1. Operate On Two Same Shape Arrays.
- If the shapes of the two arrays are exactly the same, we can calculate them directly like below.
import numpy as np def numpy_broadcasting_example_same_dimension_size_array(): # create the first array arr_1. arr_1 = np.array([3, 6, 9, 12, 15, 18]) print('arr_1 = ', arr_1) print('len(arr_1) = ', len(arr_1)) print('type(arr_1) = ', type(arr_1)) # create the second array arr_2 that has same dimension and size as arr_1. arr_2 = np.array([3, 3, 3, 3, 3, 3]) print('arr_2 = ', arr_2) print('len(arr_2) = ', len(arr_2)) print('type(arr_2) = ', type(arr_2)) # calculate arr_1 and arr_2 directly and get arr_3. arr_3 = arr_1 / arr_2 print('arr_3 = ', arr_3) print('len(arr_3) = ', len(arr_3)) print('type(arr_3) = ', type(arr_3)) if __name__ == '__main__': numpy_broadcasting_example_same_dimension_size_array()
- When you run the above example, you will get the below output in the console.
arr_1 = [ 3 6 9 12 15 18] len(arr_1) = 6 type(arr_1) = <class 'numpy.ndarray'> arr_2 = [3 3 3 3 3 3] len(arr_2) = 6 type(arr_2) = <class 'numpy.ndarray'> arr_3 = [1. 2. 3. 4. 5. 6.] len(arr_3) = 6 type(arr_3) = <class 'numpy.ndarray'>
2. Operate On Two Different Shape Arrays.
- For two arrays with different shapes, they can also be calculated。
- In order to keep the two arrays shape the same, NumPy designed a broadcast mechanism.
- The core of this mechanism is to repeat the smaller shape array a certain number of times horizontally or vertically to make it has the same dimension and size as the larger shape array.
- Numpy automatically triggers the broadcast mechanism when the two arrays being calculated have different shapes.
import numpy as np def numpy_broadcasting_example_different_dimension_size_array(): # create the first array arr_1. arr_1 = np.array([3, 6, 9, 12, 15, 18]) # reshape the arr_1 to 2 rows & 3 columns. arr_1 = arr_1.reshape(2, 3) print('arr_1 = ', arr_1) print('len(arr_1) = ', len(arr_1)) print('type(arr_1) = ', type(arr_1)) # create the second array arr_2 that has same dimension and size as arr_1. arr_2 = np.array([3, 3, 3]) print('arr_2 = ', arr_2) print('len(arr_2) = ', len(arr_2)) print('type(arr_2) = ', type(arr_2)) # calculate arr_1 and arr_2 directly and get arr_3. arr_3 = arr_1 / arr_2 print('arr_3 = ', arr_3) print('len(arr_3) = ', len(arr_3)) print('type(arr_3) = ', type(arr_3)) if __name__ == '__main__': numpy_broadcasting_example_different_dimension_size_array()
- Below is the above example execution output.
arr_1 = [[ 3 6 9] [12 15 18]] len(arr_1) = 2 type(arr_1) = <class 'numpy.ndarray'> arr_2 = [3 3 3] len(arr_2) = 3 type(arr_2) = <class 'numpy.ndarray'> arr_3 = [[1. 2. 3.] [4. 5. 6.]] len(arr_3) = 2 type(arr_3) = <class 'numpy.ndarray'>