Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Changing value detection numpy Python

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading