Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find index where elements change value numpy

Suppose I have

>>> v array([1, 1, 1, 1, 1, 2, 2, 2, 3, 4, 3, 4, 3, 4, 3, 4, 5, 5, 5]) 

Is there an efficient numpy way to find each index where the value changes? For instance, I would want some result like,

>>> index_of_changed_values(v) [0, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16] 

If this is not possible with some numpy routine, what is a fast way to do it in python? It would also be useful to me to be referred to some good numpy tutorials since I am a numpy beginner.

like image 547
Erin Avatar asked Oct 01 '13 20:10

Erin


People also ask

How do I find the index of a specific element?

To find the index of an element in a list, you use the index() function. It returns 3 as expected.

What does NP Argwhere return?

The np. argwhere() is a Numpy library function used to find the indices of array elements that are nonzero, grouped by element. The numpy argwhere() function takes an array-like parameter and returns the indices of the array elements.


1 Answers

You can get this functionality in numpy by comparing each element with it's neighbor;

v[:-1] != v[1:]   array([False, False, False, False,  True, False, False,  True,  True,     True,  True,  True,  True,  True,  True,  True, False, False], dtype=bool) 

to get the indices you use the "where" function

np.where(v[:-1] != v[1:])[0]  array([ 4,  7,  8,  9, 10, 11, 12, 13, 14, 15]) 

From here you can prepend the first element and add a one to get to the same indexing scheme you have in your question.

like image 159
kith Avatar answered Oct 15 '22 20:10

kith