pythonnumpyslicenumpy-slicingprogram-slicing

SIice a numpy array based on an interval?


Is it possible to systematically slice an 1d array of length m by an interval n in numpy? Say I have a list of 1000 values, could I break that into 10 lists of 100 values easily?


Solution

  • You can use both np.array_split() and np.split() which in fact are the same with a little note (as per np.array_split())

    From the documentation:

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

    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. For an array of length l that should be split into n sections, it returns l % n sub-arrays of size l//n + 1 and the rest of size l//n.