简体   繁体   中英

numpy: multiplying a 2D array by a 1D array

Let us say one has an array of 2D 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 would like the result:

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

Now, executing v*s is an error. Then, what is the most efficient way to go about implementing f ?

Add a new singular dimension to the vector:

v*s[:,None]

This is equivalent to reshaping 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 NumPy broadcasting rules (corresponding dimensions are either equal to each other or equal to 1).

Note that when two operands have unequal numbers of dimensions, NumPy will insert extra singular dimensions "in front" of the operand with fewer dimensions. This would make your vector (1,4) which is incompatible with (4,2). Therefore, we explicitly specify where the extra dimensions are added, in order to make the shapes compatible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM