使用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])]
杨__羊羊
湖上湖
相关分类