如何随机化一个矩阵,使行在python中保持固定

xiaoxingxing python 196

原文标题how to randomize a matrix keeping the rows fixed in python

我正在尝试随机化我的 DataFrame 的所有行但没有成功。我想要做的是来自这个矩阵

A= [ 1 2 3
     4 5 6 
     7 8 9 ]

对此

A_random=[ 4 5 6 
           7 8 9 
           1 2 3 ]

我试过 np.random.shuffle 但它不起作用。

我在 Google Colaboratory 环境中工作。

原文链接:https://stackoverflow.com//questions/71909873/how-to-randomize-a-matrix-keeping-the-rows-fixed-in-python

回复

我来回复
  • Dan Babington的头像
    Dan Babington 评论

    如果你想用np.random.shuffle进行这项工作,那么一种方法是将行提取到ArrayLike结构中,将它们打乱,然后重新创建DataFrame

    A = pandas.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    extracted_rows = A.values.tolist()  # Each row is an array element, so rows will remain fixed but their order shuffled
    np.random.shuffle(extracted_rows)
    A_random = pandas.DataFrame(extracted_rows)
    
    2年前 0条评论