Numpy: Multiplying a 2D Array by a 1D Array

Let's say one has an array of two-dimensional vectors:

v = np.array([ [1, 1], [1, 1], [1, 1], [1, 1]])
v.shape = (4, 2)

And an array of scalars:

s = np.array( [2, 2, 2, 2] )
s.shape = (4,)

I need the result:

f(v, s) = np.array([ [2, 2], [2, 2], [2, 2], [2, 2]])

Now execution v*sis a mistake. Then, what is the most efficient way to implement it f?

+4
source share
1 answer

Add a new special dimension to the vector:

v*s[:,None]

This is equivalent to changing the shape of the vector as (len (s), 1). Then the shapes of the multiplied objects will be (4,2) and (4,1), which are compatible due to the NumPy broadcast rules (the corresponding sizes are either equal to each other or equal to 1).

, , NumPy "" . (1,4), (4,2). , , .

+8

Source: https://habr.com/ru/post/1544820/


All Articles