python - 将子集复制到数组的其余部分的 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
解决方案
方法#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]
推荐阅读
- modelica - 如何找到振荡器的谐振频率?
- jquery - 无法使用 jquery 减少 div
- sql - 请帮助使用 GROUP BY 构建 SQL SELECT 请求
- ios - 核心数据崩溃:尝试访问使用谓词获得的数据时出现 EXC_BAD_ACCESS
- sql-server - SQLServer Docker:如何备份和恢复数据 *volume*?
- python - Python-Telegram-Bot:结束对话后无法重用 ConversationHandler
- go - Type.Field 和 Value.Field 有什么区别?
- python-3.x - Google Cloud 错误:错误:INVALID_ARGUMENT:请求包含无效参数
- java - 如何配置 log4j.properties 文件以打印进行日志记录的类的父类?
- angular - 如何将路由事件 URL 绑定到 Angular 中的 HTML 模板