Diego Silvera
Diego Silvera

Reputation: 201

Replacing each row with a column

Given an array X of shape (n, m) and another given number l how can I get an array Y of shape (n, l, m, l) where Y[i, j, :, :] is the null matrix that has been replaced the j-th column by the i-th row of X.

For example, if

X = np.array([
    [1, 2, 3, 4],
    [2, 3, 4, 5],
    [3, 4, 5, 6]])
l = 5

then

Y[2, 3] = np.array([
    [0, 0, 0, 3, 0],
    [0, 0, 0, 4, 0],
    [0, 0, 0, 5, 0],
    [0, 0, 0, 6, 0]
])

Thank you.

Upvotes: 1

Views: 57

Answers (1)

Paul Panzer
Paul Panzer

Reputation: 53029

Use np.einsum:

Y = np.zeros((n, l, m, l))
np.einsum('ijkj->jik', Y)[...] = X

Upvotes: 1

Related Questions