I have a 1D numpy array. The difference between two succeeding values in this array is either one or larger than one. I want to cut the array into parts for every occurrence that the difference is larger than one. Hence:
arr = numpy.array([77, 78, 79, 80, 90, 91, 92, 100, 101, 102, 103, 104])
should become
[array([77, 78, 79, 80]), array([90, 91, 92]), array([100, 101, 102, 103, 104])]
I have the following code that does the trick but I have the feeling I am being to complicated here. There has to be a better/more pythonic way. Anyone with a more elegant approach?
import numpy
def split(arr, cut_idxs):
empty_arr = []
for idx in range(-1, cut_idxs.shape[0]):
if idx == -1:
l, r = 0, cut_idxs[0]
elif (idx != -1) and (idx != cut_idxs.shape[0] - 1):
l, r = cut_idxs[idx] + 1, cut_idxs[idx + 1]
elif idx == cut_idxs.shape[0] - 1:
l, r = cut_idxs[-1] + 1, arr.shape[0]
empty_arr.append(arr[l:r + 1])
return empty_arr
arr = numpy.array([77, 78, 79, 80, 90, 91, 92, 100, 101, 102, 103, 104])
cuts = numpy.where(numpy.ediff1d(arr) > 2)[0]
print split(arr, cuts)