SIice a numpy array based on an interval?

1.3k views Asked by At

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?

2

There are 2 answers

0
Timbus Calin On BEST ANSWER

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.

0
NaN On

array_split allows one to split with unequal spacing as well, should this ever meet your needs

ar = np.arange(0, 20, dtype='int')

s = [2, 7, 12, 17]

np.array_split(ar, s)
Out[80]: 
[array([0, 1]),
 array([2, 3, 4, 5, 6]),
 array([ 7,  8,  9, 10, 11]),
 array([12, 13, 14, 15, 16]),
 array([17, 18, 19])]