Created
December 6, 2020 06:18
-
-
Save asifr/1862fe5db469cc99c06387800f6b1dff to your computer and use it in GitHub Desktop.
Group consecutive values and return unique ids
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import numpy as np | |
| def generate_ids(x): | |
| partitions = lambda x: np.where(x[1:] != x[:-1])[0] + 1 | |
| inds = np.split(np.arange(len(x)), partitions(x)) | |
| ids = np.zeros(len(x)) | |
| for k, p in enumerate(inds): | |
| ids[p] = k | |
| return ids | |
| x = np.array([0,0,0,1,1,1,1,1,0,0,0,1,1,1,0,1]) | |
| generate_ids(x) # array([0., 0., 0., 1., 1., 1., 1., 1., 2., 2., 2., 3., 3., 3., 4., 5.]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment