Python – How to multiply numpy 2D array with numpy 1D array

numpypython

The two arrays:

a = numpy.array([[2,3,2],[5,6,1]])
b = numpy.array([3,5])
c = a * b

What I want is:

c = [[6,9,6],
     [25,30,5]]

But, I am getting this error:

ValueError: operands could not be broadcast together with shapes (2,3) (2)

How to multiply a nD array with 1D array, where len(1D-array) == len(nD array)?

Best Answer

You need to convert array b to a (2, 1) shape array, use None or numpy.newaxis in the index tuple:

import numpy
a = numpy.array([[2,3,2],[5,6,1]])
b = numpy.array([3,5])
c = a * b[:, None]

Here is the document.