我正在尝试将数组拆分为n个部分。有时这些部分的大小相同,有时它们的大小不同。
我正在尝试使用:
split = np.split(list, size)
当大小平均分配到列表中时,这可以正常工作,但否则失败。有没有办法做到这一点,将填补'垫最后的数组与额外的'少数'元素?
答案 0 :(得分:22)
您在寻找np.array_split吗? 这是docstring:
Split an array into multiple sub-arrays.
Please refer to the ``split`` documentation. The only difference
between these functions is that ``array_split`` allows
`indices_or_sections` to be an integer that does *not* equally
divide the axis.
See Also
--------
split : Split array into multiple sub-arrays of equal size.
Examples
--------
>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
[array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7.])]
http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.array_split.html
答案 1 :(得分:3)
def split_padded(a,n):
padding = (-len(a))%n
return np.split(np.concatenate((a,np.zeros(padding))),n)
答案 2 :(得分:0)
通过将索引作为列表传递,可以将数组拆分为不相等的块 例子
**x = np.arange(10)**
x
(0,1,2,3,4,5,6,7,8,9)
np.array_split(x,[4])
[array([0,1,2,3],dtype = int64),
array([4,5,6,7,8,9],dtype = int64)**