Numpy shuffle multidimensional array by row only, keep column order unchanged

You can use numpy.random.shuffle().

This function only shuffles the array along the first axis of a
multi-dimensional array. The order of sub-arrays is changed but their
contents remains the same.

In [2]: import numpy as np                                                                                                                                                                                  

In [3]:                                                                                                                                                                                                     

In [3]: X = np.random.random((6, 2))                                                                                                                                                                        

In [4]: X                                                                                                                                                                                                   
Out[4]: 
array([[0.71935047, 0.25796155],
       [0.4621708 , 0.55140423],
       [0.22605866, 0.61581771],
       [0.47264172, 0.79307633],
       [0.22701656, 0.11927993],
       [0.20117207, 0.2754544 ]])

In [5]: np.random.shuffle(X)                                                                                                                                                                                

In [6]: X                                                                                                                                                                                                   
Out[6]: 
array([[0.71935047, 0.25796155],
       [0.47264172, 0.79307633],
       [0.4621708 , 0.55140423],
       [0.22701656, 0.11927993],
       [0.20117207, 0.2754544 ],
       [0.22605866, 0.61581771]])

For other functionalities you can also check out the following functions:

The function random.Generator.permuted is introduced in Numpy’s 1.20.0 Release.

The new function differs from shuffle and permutation in that the
subarrays indexed by an axis are permuted rather than the axis being
treated as a separate 1-D array for every combination of the other
indexes. For example, it is now possible to permute the rows or
columns of a 2-D array.

Leave a Comment