簡體   English   中英

numpy數組中某些行的隨機排序

[英]Shuffle ordering of some rows in numpy array

我想在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]])

您可以使用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]])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM