How can I make a numpy function that detects the indexes where there is a change in values? Sop since the first number is unique it will include that and from index 0 to 1 the number changes from 24 to 27. So it will have 0 as the first index and so on.
import numpy as np
digit_vals = np.array([24, 27, 27, 27,
28, 28, 28, 31])
Expected output:
[0, 1, 4, 7]
CodePudding user response:
You can do this:
np.where(np.diff(digit_vals, prepend=np.nan))
CodePudding user response:
import numpy as np
digit_vals = np.array([24, 27, 27, 27,
28, 28, 28, 31])
unique = set(digit_vals)
[digit_vals.tolist().index(i) for i in unique]
Output:
[0, 1, 4, 7]
Find the unique elements and then convert the array to a list. Use the index() function of the list to get the index at the first occurrence of any element in a list.
CodePudding user response:
The answer from @SergedeGossondeVarennes is way more pythonist, you should definitely consider his answer, but this is an other way to do it for diversity :
import numpy as np
digit_vals = np.array([24, 27, 27, 27,
28, 28, 28, 31])
res = np.where(digit_vals[:-1] != digit_vals[1:])[0] 1
res = np.insert(res, 0, 0, axis=0)
