Shuffle a numpy array

前端 未结 3 1417
一向
一向 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:08

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

提交回复
热议问题