【发布时间】:2020-08-24 14:22:52
【问题描述】:
使用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.choice 和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])]
【问题讨论】:
-
你为什么使用
np.random?你想从原始数组中获取连续的块还是随机元素? -
随机元素,甚至 np.split 给出了连续的块:-(
-
使用
replace=False。 -
@Divakar:这是for循环的不同迭代,因此将被替换。
-
会鼓励你把这些放在一起并发布你自己的答案。