Python NumPy:将数组拆分为不等子数组

11

我正在尝试将一个数组分成 n 个部分。有时这些部分的大小相同,有时它们的大小不同。

我尝试使用以下代码:

split = np.split(list, size)

当大小能够整除列表时,这个代码可以正常工作,但在其他情况下则会失败。有没有一种方法可以实现这个功能,即用额外的元素“填充”最后一个数组?

4个回答

39

您是否正在寻找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


3
def split_padded(a,n):
    padding = (-len(a))%n
    return np.split(np.concatenate((a,np.zeros(padding))),n)

1
这个答案中有什么是什么? - anurag
1
如果尺寸很大,它就无法工作。 - Marjan
在StackOverflow上写一个没有任何解释的答案并不是一种推荐的做法,我敦促您了解如何撰写一个好的答案。如何撰写一个好的答案 - Arka Mukherjee

2

简短方法: 使用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

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)**

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接