首页 > 解决方案 > 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):

标签: arraysnumpymatrixshuffle

解决方案


您所要求的可以通过所谓的矩阵共轭来完成:

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]])

推荐阅读