Changing value detection numpy Python

Viewed 60

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]
1 Answers

You can do this:

np.where(np.diff(digit_vals, prepend=np.nan)) 

What happens here is that you first use np.diff. Its parameters are the following: 1) an array, your digit_vals, and 2) prepend = np.nan. The last simply is which values append to digit_vals along axis prior to performing the difference.

np.where() return the positions at which the differences occur.

Related