To avoid the XY problem, here is an example of what I need. Given the sorted integer input array
[1 1 1 2 2 3], I would like to produce the following slices, together with their index:
0: slice(0,3) 1: slice(3,5) 2: slice(5,6)
(Both the index and the slice will be used to index/slice into some other arrays.)
I think this could be solved with the itertools.groupby(). Partly because I am learning NumPy, and partly because evidence suggests that
groupby() may be inefficient, I would like to do this in NumPy. The code below seems to do what I want.
from __future__ import print_function import numpy as np if __name__=='__main__': arr = np.array([1, 1, 1, 2, 2, 3]) print(arr) mask = np.ediff1d(arr, to_begin=1, to_end=1) indices = np.where(mask) for i in np.arange(indices.size-1): print('%d: slice(%d,%d)' % (i, indices[i], indices[i+1]))
Is there a cleaner / more efficient way of doing this?