Skip to content

Instantly share code, notes, and snippets.

@asifr
Created December 6, 2020 06:18
Show Gist options
  • Select an option

  • Save asifr/1862fe5db469cc99c06387800f6b1dff to your computer and use it in GitHub Desktop.

Select an option

Save asifr/1862fe5db469cc99c06387800f6b1dff to your computer and use it in GitHub Desktop.
Group consecutive values and return unique ids
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