3

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 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

@tlentali If only there was an explanation of it...
I used a np.digitize function to get the values of the digit_vals which are [0, 1, 4, 7] but I cannot use ur function o n it for some reason. It gives me an error ValueError: setting an array element with a sequence.. Would you have any idead on how I could fix it?
@bullselcuk Can you edit your question with the prior step?
@SergedeGossondeVarennes ok will do so

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.