使用 Numpy 将数组划分为 N 个块 [英] Partition array into N chunks with Numpy
问题描述
有这个 怎么做你把一个列表分成大小均匀的块?用于将数组拆分为块.无论如何,对于使用 Numpy 的巨型数组,是否可以更有效地执行此操作?
来自文档:
<预><代码>>>>x = np.arange(8.0)>>>np.array_split(x, 3)[数组([ 0., 1., 2.]), 数组([ 3., 4., 5.]), 数组([ 6., 7.])]与 numpy.split
相同,但如果组的长度不相等,则不会引发异常.
如果块数 > len(array) 你得到嵌套在里面的空白数组,为了解决这个问题 - 如果你的拆分数组保存在 a
中,那么你可以通过以下方式删除空数组:
[x for x in a if x.size >0]
如果您愿意,只需将其保存回 a
.
There is this How do you split a list into evenly sized chunks? for splitting an array into chunks. Is there anyway to do this more efficiently for giant arrays using Numpy?
Try numpy.array_split
.
From the documentation:
>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
[array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7.])]
Identical to numpy.split
, but won't raise an exception if the groups aren't equal length.
If number of chunks > len(array) you get blank arrays nested inside, to address that - if your split array is saved in a
, then you can remove empty arrays by:
[x for x in a if x.size > 0]
Just save that back in a
if you wish.
这篇关于使用 Numpy 将数组划分为 N 个块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!