简体   繁体   English

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

[英]Shuffle ordering of some rows in numpy array

I want to shuffle the ordering of only some rows in a numpy array. 我想在numpy数组中只调整一些行的顺序。 These rows will always be continuous (eg shuffling rows 23-80). 这些行将始终是连续的(例如,洗牌行23-80)。 The number of elements in each row can vary from 1 (such that the array is actually 1D) to 100. 每行中的元素数量可以从1(使得数组实际为1D)变为100。

Below is example code to demonstrate how I see the method shuffle_rows() could work. 下面是示例代码,演示我如何看待shuffle_rows()方法可以工作。 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 . 您可以使用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]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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