首页 > 解决方案 > 将子集复制到数组的其余部分的 Numpy 方式?

问题描述

我正在尝试将矩阵的第一行复制到其他行。有没有更“麻木”的方式来做到这一点?

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

标签: pythonnumpy

解决方案


方法#1

这是一种矢量化方法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]]

方法#2

我们也可以简单地排列列以获得所需的输出 -

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]

推荐阅读