【问题标题】:Random shuffle of array, but keep diagonal fixed数组的随机洗牌,但保持对角线固定
【发布时间】:2020-01-21 11:45:58
【问题描述】:

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

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

我想随机洗牌,但保持对角线中的 1 固定。当我这样做时

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

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

有人知道解决办法吗?

谢谢!

【问题讨论】:

    标签: python numpy random shuffle


    【解决方案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)]
    

    【讨论】:

      猜你喜欢
      • 2010-12-03
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      相关资源
      最近更新 更多