Adding and multiplying columns of a numpy array with another array
I have an array 2D
numpy
x
and an 1D
numpy
array y
:
import numpy as np x = np.arange(12).reshape((4, 3)) y = np.array(([1.0,2.0,3.0,4.0])
I want to multiply / add a column vector y.reshape((4,1))
to each column x
. I tried the following:
y1 = y.reshape((4,1)) y1 * x
gives
array([[ 0., 1., 2.],
[ 6., 8., 10.],
[ 18., 21., 24.],
[ 36., 40., 44.]])
which is what I wanted. I also found
array([[ 1., 2., 3.],
[ 5., 6., 7.],
[ 9., 10., 11.],
[ 13., 14., 15.]])
with y1 + x
.
I would like to know if there is a better (more efficient) way to achieve the same!
source to share
NumPy supports this through broadcasts. Your code was using broadcast and this is the most efficient way to do something. I usually write it like:
>>> x * y[..., np.newaxis]
array([[ 0., 1., 2.],
[ 6., 8., 10.],
[ 18., 21., 24.],
[ 36., 40., 44.]])
To see if this is equivalent:
>>> z = y[..., np.newaxis]
>>> z.shape
(4, 1)
You can also see that NumPy does not copy data, it just iterates over the same memory
>>> z.base is y
True
More details here
source to share
You can use np.add
and np.multiply
:
>>> np.add(y1,x)
array([[ 1., 2., 3.],
[ 5., 6., 7.],
[ 9., 10., 11.],
[ 13., 14., 15.]])
>>> np.multiply(y1,x)
array([[ 0., 1., 2.],
[ 6., 8., 10.],
[ 18., 21., 24.],
[ 36., 40., 44.]])
Or for changes in place, you can use the methods iadd
and imul
for numpy ndarray
:
>>> x.__iadd__(y1)
array([[ 1, 2, 3],
[ 5, 6, 7],
[ 9, 10, 11],
[13, 14, 15]])
>>> x = np.arange(12).reshape((4, 3))
>>> x.__imul__(y1)
array([[ 0, 1, 2],
[ 6, 8, 10],
[18, 21, 24],
[36, 40, 44]])
Notice, that:
In-place, the operation will perform computations using the precision specified by the data type of the two operands, but will silently entangle the result (if necessary) so that it can fit back into the array. Therefore, for mixed computations, the precision of A {op} = B may differ from A = A {op} B. For example, suppose a = ones ((3,3)). Then a + = 3j is different from a = a + 3j: while both of them perform the same calculation, a + = 3 distinguishes the result so that it goes back to a, whereas a = a + 3j re-associates the name a with the result ...
source to share