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.
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)