Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multiply numpy 2D array with numpy 1D array?

Tags:

python

numpy

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

like image 817
Ashwin Nanjappa Avatar asked Apr 26 '13 06:04

Ashwin Nanjappa


People also ask

How do you multiply a 1-D matrix by a 2D matrix?

To find the matrix product of a 2D and a 1D array, use the numpy. matmul() method in Python Numpy. If the second argument is 1-D, it is promoted to a matrix by appending a 1 to its dimensions. After matrix multiplication the appended 1 is removed.

How do you multiply the two Numpy arrays with each other?

multiply() function is used when we want to compute the multiplication of two array. It returns the product of arr1 and arr2, element-wise.

Which function in Numpy is used to combine 1-D and 2D array?

In numpy concatenate arrays we can easily use the function np. concatenate(). It can be used to concatenate two arrays either row-wise or column-wise.


2 Answers

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.

like image 108
HYRY Avatar answered Oct 07 '22 08:10

HYRY


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]]
like image 33
Mike T Avatar answered Oct 07 '22 08:10

Mike T