Shuffle ordering of some rows in numpy array Shuffle ordering of some rows in numpy array numpy numpy

Shuffle ordering of some rows in numpy array


You can use np.random.shuffle. This shuffles the rows themselves, not the elements within the rows.

From the docs:

This function only shuffles the array along the first index of a multi-dimensional array

As an example:

import numpy as npdef shuffle_rows(arr,rows):    np.random.shuffle(arr[rows[0]:rows[1]+1])a = np.arange(20).reshape(4, 5)print(a)# array([[ 0,  1,  2,  3,  4],#        [ 5,  6,  7,  8,  9],#        [10, 11, 12, 13, 14],#        [15, 16, 17, 18, 19]])shuffle_rows(a,[1,3])print(a)#array([[ 0,  1,  2,  3,  4],#       [10, 11, 12, 13, 14],#       [15, 16, 17, 18, 19],#       [ 5,  6,  7,  8,  9]])shuffle_rows(a,[1,3])print(a)#array([[ 0,  1,  2,  3,  4],#       [10, 11, 12, 13, 14],#       [ 5,  6,  7,  8,  9],#       [15, 16, 17, 18, 19]])