Skip to content
Advertisement

Replace consecutive identic elements in the beginning of an array with 0

I want to replace the N first identic consecutive numbers from an array with 0.

JavaScript

OUT -> np.array([0, 0, 0, 0 2, 3, 1, 2, 3, 2, 2, 2, 3, 3, 3, 1, 1, 2, 2])

Loop works, but what would be a faster-vectorized implementation?

JavaScript

Advertisement

Answer

You can use argmax on a boolean array to get the index of the first changing value.

Then slice and replace:

JavaScript

output:

JavaScript

intermediate array:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement