使用 Numpy 将数组分成 N 个不同大小的随机块

使用numpy.array_splits,您可以将数组拆分为大小相等的块。有没有办法根据列表将它分成块?


我如何将这个数组分成 4 个块,每个块由中给定的块的大小决定chunk_size,并由数组中的随机值组成?


import numpy as np

np.random.seed(13)

a = np.arange(20)

chunk_size = [10, 5, 3, 2]

dist = [np.random.choice(a, c) for c in chunk_size]

print(dist)

但正如预期的那样,我得到了多次重复:


[array([18, 16, 10, 16,  6,  2, 12,  3,  2, 14]),

 array([ 5, 13, 10,  9, 11]), array([ 2,  0, 19]), array([19, 11])]

例如,


16 在第一个块中包含两次

10 包含在第一个和第二个块中

使用np.split,这是我得到的答案:


>>> for s in np.split(a, chunk_size):

...     print(s.shape)

...

(10,)

(0,)

(0,)

(0,)

(18,)

使用np.random.choiceand replace=False,仍然给出重复的元素:


import numpy as np

np.random.seed(13)

a = np.arange(20)

chunk_size = [10, 5, 3, 2]

dist = [np.random.choice(a, c, replace=False) for c in chunk_size]

print(dist)

虽然每个块现在不包含重复项,但它不会阻止,例如,第一个和第二个块中都包含 7:


[array([11, 12,  0,  1,  8,  5,  7, 15, 14, 13]),

 array([16,  7, 13,  9, 19]), array([1, 4, 2]), array([15, 12])]


沧海一幻觉
浏览 224回答 2
2回答

杨__羊羊

确保 的每个元素a恰好包含在一个块中的一种方法是a首先创建一个随机排列,然后将其拆分为np.split。为了np.split从中获取一组拆分索引chunk_size,您可以使用np.cumsum.例子>>> import numpy as np>>> np.random.seed(13)>>> a = np.arange(20)>>> b = np.random.permutation(a)>>> barray([11, 12,  0,  1,  8,  5,  7, 15, 14, 13,        3, 17,  9,  4,  2,  6, 19, 10, 16, 18])>>> chunk_size = [10, 5, 3, 2]>>> np.cumsum(chunk_size)array([10, 15, 18, 20])>>> np.split(b, np.cumsum(chunk_size))[array([11, 12,  0,  1,  8,  5,  7, 15, 14, 13]), array([ 3, 17,  9,  4,  2]), array([ 6, 19, 10]), array([16, 18]), array([], dtype=int64)]您可以通过省略 中的最后一个值来避免尾随空数组chunk_size,因为它由 的大小a和先前值的总和暗示:>>> np.split(b, np.cumsum(chunk_size[:-1]))  # [10, 5, 3] -- 2 is implied[array([11, 12,  0,  1,  8,  5,  7, 15, 14, 13]), array([ 3, 17,  9,  4,  2]), array([ 6, 19, 10]), array([16, 18])]

湖上湖

import numpy as npnp.random.seed(13)dist = np.arange(0, 3286, 1)chunk_size = [975, 708, 515, 343, 269, 228, 77, 57, 42, 33, 11, 9, 7, 4, 3, 1, 1, 1, 1, 1]dist = [np.random.choice(dist,_, replace=False) for _ in chunk_size]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python