在python中以一种不完全可怕的方式随机洗牌矩阵

2024-09-30 00:28:35 发布

您现在位置:Python中文网/ 问答频道 /正文

对于数据科学应用程序,我需要在开始工作之前随机洗牌矩阵中的行

是否有一种方法可以做到这一点,而不仅仅是获取索引,对索引进行无序处理,然后将无序处理后的索引传递给矩阵?例如:

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

谢谢大家!


Tags: 数据方法应用程序datanprange矩阵科学
2条回答

numpy.random.shuffle()应该可以做到这一点

import numpy as np
mat = np.array(range(16)).reshape(4,4)

print(mat,'\n')

np.random.shuffle(mat) 

print(mat)

输出:

[[ 0  1  2  3]
[ 4  5  6  7]
[ 8  9 10 11]
[12 13 14 15]]

[[12 13 14 15]
[ 4  5  6  7]
[ 0  1  2  3]
[8  9 10 11]] 

使用python(而不是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]]

相关问题 更多 >

    热门问题