Python numpy.array_split()奇数行为

Python numpy.array_split()奇数行为,python,numpy,pandas,Python,Numpy,Pandas,我正在尝试将包含周期数据的大型数据帧拆分为周期长度相等或接近相等的较小数据帧。在我的数据不允许相等拆分之前,数组_拆分一直工作得很好(在500000个周期中工作得很好,但在1190508中工作得不好)。我希望各部分以1000个周期为增量(除了最后一帧会更少) 以下是场景: d = { 'a': pd.Series(random(1190508)), 'b': pd.Series(random(1190508)), 'c': pd.Series(random(1190508)), } frame

我正在尝试将包含周期数据的大型数据帧拆分为周期长度相等或接近相等的较小数据帧。在我的数据不允许相等拆分之前,数组_拆分一直工作得很好(在500000个周期中工作得很好,但在1190508中工作得不好)。我希望各部分以1000个周期为增量(除了最后一帧会更少)

以下是场景:

d = {
'a': pd.Series(random(1190508)),
'b': pd.Series(random(1190508)),
'c': pd.Series(random(1190508)),
}

frame = pd.DataFrame(d)

cycles = 1000  
sections = math.ceil(len(frame)/cycles)

split_frames = np.array_split(frame, sections)
文档显示array_split基本上可以拆分偶数组,然后在最后生成更小的组,因为数据不能被平均拆分。这就是我想要的,但是现在,如果我查看这个新的
split_frames列表中每个帧的长度

split_len = pd.DataFrame([len(a) for a in split_frame])

split_len.to_csv('lengths.csv')
前698帧的长度为1000个元素,但其余(699到1190帧)的长度为999个元素

无论我为
节传递的是什么数字(四舍五入、偶数或其他任何数字),它似乎都会使这种随机发生的长度中断

我很难理解为什么除了文档中的最后一个一样,它没有创建相同的帧长度:

>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
    [array([ 0.,  1.,  2.]), array([ 3.,  4.,  5.]), array([ 6.,  7.])] 

感谢您的帮助,谢谢

array\u split
不会生成数量相等的部分,并且会生成一个包含剩余部分的部分。如果将长度为
l
的数组拆分为
n
节,则会生成
l%n
大小为
l//n+1
的节,其余大小为
l//n
。有关更多详细信息,请参阅。(这确实应该在文档中解释。)

正如@user2357112所写,
array\u split
并不像您想象的那样。。。但是通过查看文档,无论如何,很难知道它是做什么的。事实上,我得说它的行为是未定义的。我们期望它返回一些东西,但我们不知道这些东西将具有什么属性

为了得到您想要的,我将使用
numpy.split
提供自定义索引的功能。例如:

def greedy_split(arr, n, axis=0):
    """Greedily splits an array into n blocks.

    Splits array arr along axis into n blocks such that:
        - blocks 1 through n-1 are all the same size
        - the sum of all block sizes is equal to arr.shape[axis]
        - the last block is nonempty, and not bigger than the other blocks

    Intuitively, this "greedily" splits the array along the axis by making
    the first blocks as big as possible, then putting the leftovers in the
    last block.
    """
    length = arr.shape[axis]

    # compute the size of each of the first n-1 blocks
    block_size = np.ceil(length / float(n))

    # the indices at which the splits will occur
    ix = np.arange(block_size, length, block_size)

    return np.split(arr, ix, axis)
一些例子:

>>> x = np.arange(10)
>>> greedy_split(x, 2)
[array([0, 1, 2, 3, 4]), array([5, 6, 7, 8, 9])]
>>> greedy_split(x, 3)
[array([0, 1, 2, 3]), array([4, 5, 6, 7]), array([8, 9])]
>>> greedy_split(x, 4)
[array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8]), array([9])]

其他人正在解释的一个简单示例:

In [21]: [len(x)for x in np.array_split(np.arange(1000),12)]
Out[21]: [84, 84, 84, 84, 83, 83, 83, 83, 83, 83, 83, 83]

如何访问每次拆分的结果

x = np.arange(8.0)
y=np.数组_分割(x,3) [数组([0,1,2.]),数组([3,4,5.]),数组([6,7.])]

如何得到y(1),y(2),y(3)