Can someone please help me to understand how broadcasting works below in np.where() function ?
x = np.arange(9.).reshape(3, 3)
np.where(x < 5, x, -1) # Note: broadcasting.
array([[ 0., 1., 2.],
[ 3., 4., -1.],
[-1., -1., -1.]])
Can someone please help me to understand how broadcasting works below in np.where() function ?
x = np.arange(9.).reshape(3, 3)
np.where(x < 5, x, -1) # Note: broadcasting.
array([[ 0., 1., 2.],
[ 3., 4., -1.],
[-1., -1., -1.]])
Let's look at the individual pieces
x = np.arange(9).reshape(3, 3)
>>> x
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
Notice that x < 5
makes an array of booleans:
>>> x < 5
array([[ True, True, True],
[ True, True, False],
[False, False, False]]
Plugging this inside np.where
:
>>> np.where(x < 5, x, -1)
array([[ 0, 1, 2],
[ 3, 4, -1],
[-1, -1, -1]])
Notice that -1
has been broadcasted to match the dimensions of x < 5
:
array([[-1, -1, -1],
[-1, -1, -1],
[-1, -1, -1]])
Since x
already has the correct dimensions, it does not need any broadcasting.