arrays - Shuffle a square numpy array, but retain correspondence between row and column indices
问题描述
If I have a square and symmetric matrix, for example,
[[0 3 2]
[3 8 4]
[2 4 5]]
I do not want to shuffle rows only or columns only. instead,
how can I, for example (not the following in the strict order as written, but instead at random):
- shuffle the matrix in numpy so that row and column 1 are moved together to row and column 3,
- while row and column 3 are moved to row and column 2
- and row and column 2 are moved to row and column 1
解决方案
您所要求的可以通过所谓的矩阵共轭来完成:
perm_mat = np.random.permutation(np.eye(len(a),dtype=np.int))
out = (perm_mat @ a) @ (np.linalg.inv(perm_mat))
输出(当然是随机的):
array([[8., 4., 3.],
[4., 5., 2.],
[3., 2., 0.]])
或者可以通过切片来完成:
np.random.seed(1)
orders = np.random.permutation(np.arange(len(a)))
a[orders][:,orders]
输出:
array([[0, 2, 3],
[2, 5, 4],
[3, 4, 8]])
推荐阅读
- vb.net - 'String' 类型的值不能转换为 'String()'
- r - 在 print.tbl 中使用个人打印方法
- javascript - 如何观看 google dataLayer 对象?
- codenameone - 代号一种具有百分比宽度和自适应高度的自定义布局
- python - Pandas Dataframe groupby:一次应用多个 lambda 函数
- java - NumberFormat.getCurrencyInstance() 不返回语言环境中国和法国的货币符号 (jdk-1.8)
- c# - 用户数据未显示在模态中,但在单击按钮时会打开新选项卡,但第一条记录除外
- java - TokenEnhancer 不仅向 jwt 添加了附加信息,还向响应对象添加了附加信息
- google-cloud-platform - 通过 jenkins 推送 docker 镜像
- django - “WSGIRequest”对象没有属性“thema”