python – Split numpy array into monotonically increasing arrays

Question:

There is a numpy array like this:

array([ 538,   539,   540,   542,   665,   1152,
        1205,  1243,  1258,  1506,  557,   644,
        662,   1151,  1175], dtype=int64)

How can I split it into other arrays, is there any built in numpy ways?

In the array above, the values ​​go in ascending order, as soon as the number is less than the previous one, then it needs to be shoved into the next array. Is it possible to do this with numpy without looping through all the numbers in the array?

[538,  539,  540,  542,  665, 1152, 1205, 1243, 1258, 1506]
[557,  644,  662, 1151, 1175]

Answer:

import numpy as np

a = np.array([ 538,   539,   540,   542,   665,   1152,
              1205,  1243,  1258,  1506,  557,   644,
               662,  1151,  1175], dtype=np.int64)

Let's use vector functions: np.diff () , np.where () and np.split () :

In [26]: splitted = np.split(a, np.where(np.diff(a) < 0)[0] + 1)

In [27]: splitted
Out[27]:
[array([ 538,  539,  540,  542,  665, 1152, 1205, 1243, 1258, 1506], dtype=int64),
 array([ 557,  644,  662, 1151, 1175], dtype=int64)]

Step by step:

In [28]: np.diff(a)
Out[28]: array([   1,    1,    2,  123,  487,   53,   38,   15,  248, -949,   87,   18,  489,   24], dtype=int64)
#              539-538, ...,     665-542, ...,                       557-1506, ...

In [29]: np.where(np.diff(a) < 0)[0]
Out[29]: array([9], dtype=int64)

In [30]: np.split(a, np.where(np.diff(a) < 0)[0] + 1)
Out[30]:
[array([ 538,  539,  540,  542,  665, 1152, 1205, 1243, 1258, 1506], dtype=int64),
 array([ 557,  644,  662, 1151, 1175], dtype=int64)]
Scroll to Top