在python中以一种不完全丑陋的方式随机洗牌一个矩阵

问题描述 投票:0回答:1

对于一个DataScience应用,我需要在开始工作之前随机洗牌矩阵的行。

有没有一种方法可以做到这一点,而不只是获取索引,对索引进行洗牌,然后将洗牌后的索引传递给矩阵? 比如说

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

谢谢你!

python matrix shuffle
1个回答
0
投票

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]]

0
投票

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]] 
© www.soinside.com 2019 - 2024. All rights reserved.