37

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)?

1
  • For users searching how to create a 3D array by multiplying a 2D array with a 1D array (the title of this question), note the solution is a * b[:, None, None] (or equivalently numpy.multiply.outer(b, a)), not a * b[:, None] which corresponds to additional details in the question body. Commented Mar 23, 2023 at 10:36

2 Answers 2

47

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! What is the name of this syntax in Python: [:, None]?
@Ashwin, you can search numpy.newaxis for it.
How does this work when a has an arbitrary number of dimensions?
3

Another strategy is to reshape the second array, so it has the same number of dimensions as the first array:

c = a * b.reshape((b.size, 1))
print(c)
# [[ 6  9  6]
#  [25 30  5]]

Alternatively, the shape attribute of the second array can be modified in-place:

b.shape = (b.size, 1)
print(a.shape)  # (2, 3)
print(b.shape)  # (2, 1)
print(a * b)
# [[ 6  9  6]
#  [25 30  5]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.