Multiply each column from a 2D array by each column from another two-dimensional array

I have two Numpy arrays xwith form (m, i)and ywith form (m, j)(so the number of rows is the same). I would like to multiply each column xby each column ydifferently so that the result has a shape (m, i*j).

Example:

import numpy as np

np.random.seed(1)
x = np.random.randint(0, 2, (10, 3))
y = np.random.randint(0, 2, (10, 2))

This creates the following two arrays x:

array([[1, 1, 0],
       [0, 1, 1],
       [1, 1, 1],
       [0, 0, 1],
       [0, 1, 1],
       [0, 0, 1],
       [0, 0, 0],
       [1, 0, 0],
       [1, 0, 0],
       [0, 1, 0]])

and y:

array([[0, 0],
       [1, 1],
       [1, 1],
       [1, 0],
       [0, 0],
       [1, 1],
       [1, 1],
       [1, 1],
       [0, 1],
       [1, 0]])

Now the result should be:

array([[0, 0, 0, 0, 0, 0],
       [0, 0, 1, 1, 1, 1],
       [1, 1, 1, 1, 1, 1],
       [0, 0, 0, 0, 1, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 1],
       [0, 0, 0, 0, 0, 0],
       [1, 1, 0, 0, 0, 0],
       [0, 1, 0, 0, 0, 0],
       [0, 0, 1, 0, 0, 0]])

Currently, I have performed this operation with two nested loops on columns xand y:

def _mult(x, y):
    r = []
    for xc in x.T:
        for yc in y.T:
            r.append(xc * yc)
    return np.array(r).T

However, I'm sure there should be a more elegant solution that I did not seem to come up with.

+4
source share
1

NumPy broadcasting -

(y[:,None]*x[...,None]).reshape(x.shape[0],-1)

-

y : 10 x 2
x : 10 x 3

y[:,None] dims, 3D. 3D .

x[...,None] , dims dims, 3D.

, -

y : 10 x 1 x 2
x : 10 x 3 x 1

y[:,None]*x[...,None] y x broadcasting, (10,3,2). (10,6), .

+6

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


All Articles