python - Adding and multiplying columns of a numpy array with another array -
i have 2d
numpy
array x
, and 1d
numpy
array y
:
import numpy np x = np.arange(12).reshape((4, 3)) y = np.array(([1.0,2.0,3.0,4.0])
i want multiply / add column vector y.reshape((4,1))
each column of x
. attempted following:
y1 = y.reshape((4,1)) y1 * x
yields
array([[ 0., 1., 2.], [ 6., 8., 10.], [ 18., 21., 24.], [ 36., 40., 44.]])
which wanted. found
array([[ 1., 2., 3.], [ 5., 6., 7.], [ 9., 10., 11.], [ 13., 14., 15.]])
with y1 + x
.
know if there better (more efficient) way achieve same thing!
numpy supports via broadcasting. code used broadcasting , it's efficient way things. write as:
>>> x * y[..., np.newaxis] array([[ 0., 1., 2.], [ 6., 8., 10.], [ 18., 21., 24.], [ 36., 40., 44.]])
to see equivalent:
>>> z = y[..., np.newaxis] >>> z.shape (4, 1)
you can see numpy doesn't copy data, changes iteration on same memory internally
>>> z.base y true
read more here
Comments
Post a Comment