简体   繁体   English

随机排列一个 numpy 数组

[英]Shuffle a numpy array

I have a 2-d numpy array that I would like to shuffle.我有一个想要洗牌的二维 numpy 数组。 Is the best way to reshape it to 1-d, shuffle and reshape again to 2-d or is it possible to shuffle without reshaping?是将其重塑为 1-d、洗牌并再次重塑为 2-d 的最佳方法还是可以在不重塑的情况下进行洗牌?

just using the random.shuffle doesn't yield expected results and numpy.random.shuffle shuffles only rows:仅使用 random.shuffle 不会产生预期结果,而 numpy.random.shuffle 仅会随机播放行:

import random
import numpy as np
a=np.arange(9).reshape((3,3))
random.shuffle(a)
print a

[[0 1 2]
 [3 4 5]
 [3 4 5]]

a=np.arange(9).reshape((3,3))
np.random.shuffle(a)
print a

[[6 7 8]
 [3 4 5]
 [0 1 2]]

You can tell np.random.shuffle to act on the flattened version:你可以告诉np.random.shuffle对扁平化的版本采取行动:

>>> a = np.arange(9).reshape((3,3))
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> np.random.shuffle(a.flat)
>>> a
array([[3, 5, 8],
       [7, 6, 2],
       [1, 4, 0]])

You could shuffle a.flat :你可以洗牌a.flat

>>> np.random.shuffle(a.flat)
>>> a
array([[6, 1, 2],
       [3, 5, 0],
       [7, 8, 4]])

I think this is very importan t to note.我认为这一点非常重要
You can use random.shuffle(a) if a is 1-D numpy array.如果a是一维 numpy 数组,则可以使用random.shuffle(a) If it is ND (where N > 2) than如果它是 ND(其中 N > 2)比

random.shuffle(a) random.shuffle(a)

will spoil your data and return some random thing.会破坏你的数据并返回一些随机的东西。 As you can see here:正如你在这里看到的:

import random
import numpy as np
a=np.arange(9).reshape((3,3))
random.shuffle(a)
print a

[[0 1 2]
 [3 4 5]
 [3 4 5]]

This is a known bug (or feature?) of numpy.这是 numpy 的一个已知错误(或功能?)。

So, use only numpy.random.shuffle(a) for numpy arrays .因此,仅将numpy.random.shuffle(a)用于numpy arrays

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM