数组随机洗牌,但保持对角线固定

Random shuffle of array, but keep diagonal fixed

我定义了一个如下所示的数组:

A = np.array([[1,2,3], [4,1,5], [6,7,1]])

我想随机洗牌,但保持对角线上的 1 不变。当我这样做时

B = [0,1,2]
np.random.shuffle(B)

所有元素都被打乱,包括对角线中的 1。

有人知道解决办法吗?

谢谢!

一种方法是使用 masking -

m = ~np.eye(len(A), dtype=bool) # mask of non-diagonal elements

# Extract non-diagonal elements as a new array and shuffle in-place
Am = A[m]
np.random.shuffle(Am)

# Assign back the shuffled values into non-diag positions of input
A[m] = Am

另一种方法是生成扁平化索引,然后洗牌并分配 -

idx = np.flatnonzero(m)
A.flat[idx] = A.flat[np.random.permutation(idx)]