如何随机化一个矩阵,使行在python中保持固定
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 环境中工作。
回复
我来回复-
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年前