首页 > 解决方案 > 以不完全可怕的方式在python中随机改组矩阵

问题描述

对于 DataScience 应用程序,我需要在开始处理之前随机打乱矩阵的行。

有没有办法做到这一点,而不仅仅是获取索引,改组索引,然后将改组的索引传递给矩阵?如:

    indx = np.asarray(list(range(0, data.shape[0], 1)))
    shufIndx = shuffle(indx)
    data = data[shufIndx,:]
    return (data)

谢谢!

标签: pythonmatrixshuffle

解决方案


使用python(not numpy),您可以直接random.shuffle使用行:

import random

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

print(matrix)
random.shuffle(matrix)   # random.shuffle mutates the input and returns None
print(matrix)

样本输出:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[7, 8, 9], [1, 2, 3], [4, 5, 6]]

推荐阅读