pythonnumpyarray-broadcasting

How to broadcast this array with Numpy?


In this Python 3.11 code snippet:

import numpy as np

state = np.arange(48, dtype='u1').reshape((2, 8, 3))
pixels = [3, 4, 5]
colors = [[42, 43, 44], [0, 1, 2]]
state[0, pixels] = colors[0]  # line 1
state[1, pixels] = colors[1]  # line 2
# state[:, pixels, :] = colors  # error

I would like to replace line 1 and line 2 with a single line Numpy magic. The last line doesn't compile.


Solution

  • colors need to have the same number of dimensions as state

    state = np.arange(48, dtype='u1').reshape((2, 8, 3))
    pixels = [3, 4, 5]
    colors = np.array([[42, 43, 44], [0, 1, 2]])
    state[:,pixels,:] = np.expand_dims(colors, axis=1)
    print(state)
    

    Output

    [[[ 0  1  2]
      [ 3  4  5]
      [ 6  7  8]
      [42 43 44]
      [42 43 44]
      [42 43 44]
      [18 19 20]
      [21 22 23]]
    
     [[24 25 26]
      [27 28 29]
      [30 31 32]
      [ 0  1  2]
      [ 0  1  2]
      [ 0  1  2]
      [42 43 44]
      [45 46 47]]]