numpy数组中某些行的无序排列

2024-04-26 03:07:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想改变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]])

Tags: 方法代码importnumpy元素示例数量顺序
1条回答
网友
1楼 · 发布于 2024-04-26 03:07:15

您可以使用^{}。这将洗牌行本身,而不是行中的元素。在

docs

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

例如:

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

相关问题 更多 >

    热门问题