python - 使用 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.choice
and 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])]
解决方案
感谢迪瓦卡
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]
推荐阅读
- android - 链式调用android中Rxjava中的异常(RxJavaAssemblyException:组装)
- tsql - 对 2 个日期字段使用 WHERE 子句以及 Between 和 NULL 参数
- r - Running iterated regressions for data divided into N chunks in R
- javascript - 如何在 Angular 中使用 RxJS finalize 来限制用户点击
- sql - 带有case语句的外部应用和内部的Xpath返回错误
- ios - 在滚动iOS 13期间为UINavigationBarAppearance设置动画
- mongodb - Mongodb $unwind 数组中的数组数组
- xml - Xpath String 在使用 VB 的 UIPath 中返回 null
- hadoop - part-r-00000 没有这样的文件或目录
- javascript - 如何使用 Node.js 解析一个大的 .xlsx 文件?