varantir
varantir

Reputation: 6854

Numpy way of copying a subset over to the rest of the array?

I am trying to copy the first rows of a matrix over to the other rows. Is there a more "numpy" way of doing this?

import numpy as np

N     =   4 # NxN matrix
N_sub =   2 # Subset to be copied over to the other N-N_sub rows
X     = np.random.random([N,N]) # random matrix
sorted_indices = np.argsort(X.sum(axis = 1)) # sort according to row sum
for i in range(N_sub,N,N_sub):
    X[:,sorted_indices[i:(i+N_sub)]] = X[:,sorted_indices[0:N_sub]] # copy over

Upvotes: 0

Views: 75

Answers (1)

Divakar
Divakar

Reputation: 221514

Approach #1

Here's one vectorized approach with broadcasted assignment -

# Cols where the data is to be copied
idx = sorted_indices.reshape(-1,N_sub)

# Copy data from the first N_sub columns but introducing an extra dimension,
# which allows broadcasted vectorized assignments
X[:,idx[1:]] = X[:,None,idx[0]]

Approach #2

We can also simply permute the columns to get the desired output -

s2D = sorted_indices.reshape(-1,N_sub)
k = np.empty(s2D.size,dtype=int)
k[s2D] = np.arange(N_sub)
a = X[:,sorted_indices[:N_sub]]
Xnew = a[:,k]

Upvotes: 1

Related Questions