Home > database >  Finding continuous sequences in Python using Numpy
Finding continuous sequences in Python using Numpy

Time:12-18

Given increasing list, my purpose is to return partition of the sequence into subsequences formed by sequential numbers. I want to do it with NumPy. Now, I wish to subtract each time the value of the first element in the relevant part of the list, and ask to the indices where the value in the index equals it's index-- maybe I should modify it , but in the case where the list formed by sequential number, we can see that subtracting the first value gives just list of the indices.

CodePudding user response:

Let's pretend your numpy tag is not spurious and you have

a = np.array([10, 11, 12, 23, 30, 31, 32, 204])

If you apply np.diff, you see

d = np.diff(a)  # 1, 1, 11, 7, 1, 1, 172

Clearly, anywhere that d is not /-1, you add a split-point. Using np.flatnonzero, you can get indices that are compatible with np.split:

i = np.flatnonzero(np.abs(d) != 1)   1  # 3, 4, 7

The 1 is necessary because d is one element shorter than a, being a convolution with [-1, 1].

result = np.split(a, i) # [10, 11, 12], [23], [30, 31, 32], [204]
  • Related