简体   繁体   中英

Multiply each column of a numpy array with each value of another array

Suppose I have the following two numpy arrays:

In [251]: m=np.array([[1,4],[2,5],[3,6]])

In [252]: m
Out[252]: 
array([[1, 4],
       [2, 5],
       [3, 6]])

In [253]: c= np.array([200,400])

In [254]: c
Out[254]: array([200, 400])

I would like to get the following array in one step, but for the life of me I cannot figure it out:

In [252]: k
Out[252]: 
array([[200, 800, 400, 1600],
       [400, 1000, 800, 2000],
       [600, 1200, 1200,2400]])

The transformation you want is called the Kronecker product. Numpy has this function as numpy.kron :

In [1]: m = np.array([[1,4],[2,5],[3,6]])

In [2]: c = np.array([200,400])

In [3]: np.kron(c, m)
Out[3]: 
array([[ 200,  800,  400, 1600],
       [ 400, 1000,  800, 2000],
       [ 600, 1200, 1200, 2400]])

You can use np.concatenate along with list comprehension:

np.concatenate([m * x for x in c], axis=1)

This gives you

array([[ 200,  800,  400, 1600],
       [ 400, 1000,  800, 2000],
       [ 600, 1200, 1200, 2400]])

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