首页 > 解决方案 > 使用 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])]

例如,

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

标签: pythonnumpyrandom

解决方案


谢迪瓦卡

import numpy as np
np.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]

推荐阅读