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
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.
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.
multiply() function is used when we want to compute the multiplication of two array. It returns the product of arr1 and arr2, element-wise.
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]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With