Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Re-number disjoint sections of an array, by order of appearance

Consider an array of contiguous "sections":

x = np.asarray([
   1, 1, 1, 1,
   9, 9, 9,
   3, 3, 3, 3, 3,
   5, 5, 5,
])

I don’t care about the actual values in the array. I only care that they demarcate disjoint sections of the array. I would like to renumber them so that the first section is all 0, the second second is all 1, and so on:

desired = np.asarray([
   0, 0, 0, 0,
   1, 1, 1,
   2, 2, 2, 2, 2,
   3, 3, 3,
])

What is an elegant way to perform this operation? I don’t expect there to be a single best answer, but I think this question could provide interesting opportunities to show off applications of various Numpy and other Python features.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Assume for the sake of this question that the array is 1-dimensional and non-empty.

>Solution :

Combining np.cumsum with np.diff allows you to do this.

a = np.cumsum(np.diff(x, prepend=x[0]) != 0)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading