I want to replace the N first identic consecutive numbers from an array with 0
.
JavaScript
x
5
1
import numpy as np
2
3
4
x = np.array([1, 1, 1, 1, 2, 3, 1, 2, 3, 2, 2, 2, 3, 3, 3, 1, 1, 2, 2])
5
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
1
6
1
i = 0
2
first = x[0]
3
while x[i] == first and i <= x.size - 1:
4
x[i] = 0
5
i += 1
6
Advertisement
Answer
You can use argmax
on a boolean array to get the index of the first changing value.
Then slice and replace:
JavaScript
1
3
1
n = (x!=x[0]).argmax() # 4
2
x[:n] = 0
3
output:
JavaScript
1
2
1
array([0, 0, 0, 0, 2, 3, 1, 2, 3, 2, 2, 2, 3, 3, 3, 1, 1, 2, 2])
2
intermediate array:
JavaScript
1
6
1
(x!=x[0])
2
3
# n=4
4
# [False False False False True True True True True True True True
5
# True True True True True True True]
6