简体   繁体   中英

Shuffle ordering of some rows in numpy array

I want to shuffle the ordering of only some rows in a numpy array. These rows will always be continuous (eg shuffling rows 23-80). The number of elements in each row can vary from 1 (such that the array is actually 1D) to 100.

Below is example code to demonstrate how I see the method shuffle_rows() could work. How would I design such a method to do this shuffling efficiently?

import numpy as np
>>> a = np.arange(20).reshape(4, 5)
>>> 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]) # including rows 1, 2 and 3 in the shuffling
array([[ 0,  1,  2,  3,  4],
       [15, 16, 17, 18, 19],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

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 np


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM