numpy数组中某些行的随机排序

pir*_*pir 5 python arrays numpy shuffle

我想只改变numpy数组中某些行的顺序。这些行将始终是连续的(例如,混排第23-80行)。每行中的元素数量可以从1(这样数组实际上是1D)到100之间变化。

下面是示例代码,以演示我如何看待该方法shuffle_rows()。我将如何设计这样一种方法来有效地进行改组?

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]])
Run Code Online (Sandbox Code Playgroud)

tmd*_*son 5

您可以使用np.random.shuffle. 这会打乱行本身,而不是行内的元素。

文档

此函数仅沿多维数组的第一个索引打乱数组

举个例子:

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]])
Run Code Online (Sandbox Code Playgroud)