How to multiple different columns of 3d NumPy array by different values in one go?

Viewed 47

I have an example array like so:

x = np.array([[[1, 1, 1], [1, 1, 1], [1, 1, 1]], [[2, 2, 2], [2, 2, 2], [2, 2, 2]], [[3, 3, 3], [3, 3, 3], [3, 3, 3]]])

I can multiply all values by 2 without issues:

print(x * 2)

>>> [[[2 2 2]
  [2 2 2]
  [2 2 2]]

 [[4 4 4]
  [4 4 4]
  [4 4 4]]

 [[6 6 6]
  [6 6 6]
  [6 6 6]]]

Great!

What I need to do is multiple all arrays in the first "column" by 2, on the second "column" by 4 and on the third "column" by 3, such that:

print(result)

>>> [[[2 2 2]
  [4 4 4]
  [3 3 3]]

 [[4 4 4]
  [8 8 8]
  [6 6 6]]

 [[6 6 6]
  [12 12 12]
  [9 9 9]]]

Is there a numpy syntax to make this one go, like I did by multiplying by 2?

1 Answers

Make the factors a 3 X 1 array, and then multiply it with x:

x * np.array([2,4,3]).reshape(-1, 1)

#[[[ 2  2  2]
#  [ 4  4  4]
#  [ 3  3  3]]

# [[ 4  4  4]
#  [ 8  8  8]
#  [ 6  6  6]]

# [[ 6  6  6]
#  [12 12 12]
#  [ 9  9  9]]]

You can read more about numpy broadcasting here.

Related