pythonnumpybroadcasting

operands could not be broadcast together with shapes (5,2) (1,5)


I want multiply this two np.array, I believe it should return a (5,2) np.array, but it raise an error.

a = np.array([1, 2, 3, 4, 5])
b = np.arange(10)
b = b.reshape((5,2))
print(a.shape, b.shape)
print(b * a)

Solution

  • If you want to multiply a and b element-wise on each column, you need to add

    a = a.reshape((5,1))