[英]python numpy split array into unequal subarrays
我正在尝试将数组拆分为 n 个部分。 有时这些部分的尺寸相同,有时它们的尺寸不同。
我正在尝试使用:
split = np.split(list, size)
当大小均分到列表中时,这可以正常工作,但否则会失败。 有没有办法用额外的“少数”元素“填充”最终数组?
你在寻找 np.array_split 吗? 这是文档字符串:
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
def split_padded(a,n):
padding = (-len(a))%n
return np.split(np.concatenate((a,np.zeros(padding))),n)
简短的方法:使用: numpy.array_split
而不是numpy.split
但最好的方法是使用部分拆分来拆分数组
def cs(chunksize, fs):
sa = []
num =chunksize
while(num< fs):
sa.append(num)
num += chunksize
sa.append(num+fs%chunksize)
return sa
将函数作为参数传递给 split
for chunk in np.split(df, cs(chunksize,fs)):
chunk.to_excel('{}/{}_{:02d}.xlsx'.format(output_folder,split_name, i), index=False)
i +=1
您可以通过将索引作为列表传递来将数组拆分为不相等的块示例
**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)**
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.