Shuffle a numpy array

前端 未结 3 1428
一向
一向 2021-01-11 09:31

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?

3条回答
  •  误落风尘
    2021-01-11 10:21

    I think this is very important to note.
    You can use random.shuffle(a) if a is 1-D numpy array. If it is N-D (where N > 2) than

    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.

    So, use only numpy.random.shuffle(a) for numpy arrays.

提交回复
热议问题