随机播放一个numpy数组 [英] Shuffle a numpy array

查看:85
本文介绍了随机播放一个numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维的numpy数组,我想改组.是将其重塑为1-d,改组并重新塑形为2d的最佳方法,还是有可能在不重塑的情况下改组?

仅使用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]]

解决方案

您可以告诉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]])

I have a 2-d numpy array that I would like to shuffle. 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?

just using the random.shuffle doesn't yield expected results and numpy.random.shuffle shuffles only rows:

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:

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

这篇关于随机播放一个numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆