Broadcasting in Python array refers to how numpy handles arrays with different dimensions throughout arithmetic operations which point to certain constraints. For example, the shorter Array is broadcast across, the bigger Array to have compatible shapes.
The numpy.broadcast() method produces an object that simulates broadcasting. The np.broadcast() method takes array_like parameters and broadcast the input parameters against one another, and returns an object that encapsulates the result.
Broadcasting is the name given to the method that numpy uses to enable array arithmetic between arrays with a different shape or size. Arrays with different sizes cannot be calculated.
numpy.broadcast(in1, in2, ...)
The in1, in2 are input parameters.
The np.broadcast() method broadcasts the input parameters against one another and returns an object that encapsulates the result.
Let’s manually add two vectors using numpy broadcasting in Python.
import numpy as np x = np.array([1,2,3,4]) y = np.array([10,20,30,40]) a = np.broadcast(x, y) op = np.empty(a.shape) op.flat = [u+v for (u,v) in a] print(op)
[11. 22. 33. 44.]
Let’s compare it against built-in broadcasting.
import numpy as np x = np.array([1,2,3,4]) y = np.array([10,20,30,40]) op = x + y print(op)
[11 22 33 44]
Scalar and two-Dimensional Array
A scalar value can be used in arithmetic with a two-dimensional array. For example, we can visualize a two-dimensional array “X” with 2 rows and 3 columns added to the scalar “Y”.
import numpy as np x = np.array([[1,2,3,4], [10,20,30,40]]) y = np.array([[100,200,300,400], [500, 600, 700, 800]]) op = x + y print(op)
[[101 202 303 404] [510 620 730 840]]
Running the example prints the result of the addition of two 2D arrays.
One-Dimensional and Two-Dimensional Arrays
You can use the one-dimensional Array with a two-dimensional array.
import numpy as np x = np.array([[1,2,3,4], [10,20,30,40]]) y = np.array([100,200,300,400]) op = x + y print(op)
[[101 202 303 404] [110 220 330 440]]
Broadcasting is a convenient way that proves very useful in some practice when working with Numpy arrays but, it does not work for all cases, and in fact, it inflicts a strict rule that must be satisfied for broadcasting to be performed.
That’s it for this tutorial.