0

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.]])
Kumar
  • 41
  • 5
  • 1
    There is no broadcasting going on here. Except that the scalar at the end `-1` gets broadcasted to a 3 x 3. – piRSquared Mar 15 '18 at 06:51
  • I am not sure whether this is an example of broadcasting - You want to read [numpy docs](https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html) on `broadcasting` its actually very good – Vivek Kalyanarangan Mar 15 '18 at 06:51
  • [Nice article](http://scipy.github.io/old-wiki/pages/EricsBroadcastingDoc) for explain it, link from last line of official numpy docs from [here](https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html) – jezrael Mar 15 '18 at 06:56

1 Answers1

0

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.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135