Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying across in a numpy array

I'm trying to multiply each of the terms in a 2D array by the corresponding terms in a 1D array. This is very easy if I want to multiply every column by the 1D array, as shown in the numpy.multiply function. But I want to do the opposite, multiply each term in the row. In other words I want to multiply:

[1,2,3]   [0] [4,5,6] * [1] [7,8,9]   [2] 

and get

[0,0,0] [4,5,6] [14,16,18] 

but instead I get

[0,2,6] [0,5,12] [0,8,18] 

Does anyone know if there's an elegant way to do that with numpy? Thanks a lot, Alex

like image 974
Alex S Avatar asked Aug 29 '13 22:08

Alex S


People also ask

How do you multiply elements in a NumPy array?

A Quick Introduction to Numpy Multiply You can use np. multiply to multiply two same-sized arrays together. This computes something called the Hadamard product. In the Hadamard product, the two inputs have the same shape, and the output contains the element-wise product of each of the input values.

How do you multiply values in an array in Python?

We can use numpy. prod() from import numpy to get the multiplication of all the numbers in the list. It returns an integer or a float value depending on the multiplication result.

Can you multiply two NumPy arrays?

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


1 Answers

Normal multiplication like you showed:

>>> import numpy as np >>> m = np.array([[1,2,3],[4,5,6],[7,8,9]]) >>> c = np.array([0,1,2]) >>> m * c array([[ 0,  2,  6],        [ 0,  5, 12],        [ 0,  8, 18]]) 

If you add an axis, it will multiply the way you want:

>>> m * c[:, np.newaxis] array([[ 0,  0,  0],        [ 4,  5,  6],        [14, 16, 18]]) 

You could also transpose twice:

>>> (m.T * c).T array([[ 0,  0,  0],        [ 4,  5,  6],        [14, 16, 18]]) 
like image 100
jterrace Avatar answered Sep 23 '22 12:09

jterrace