Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get indices of numpy 1d array where value is greater than previous element

Say I generate a 1d numpy array:

r=np.random.randint(0,10,(10,))

giving, for example:

array([1, 5, 6, 7, 7, 8, 8, 0, 2, 7])

I can find the indices where the element is greater than the previous(the element to the left) like this:

for x in range(r.shape[0]):
    if r[x]>r[x-1]:
        p[x]=1
    else:
        p[x]=0
np.where(p==1)[0]

giving:

array([1, 2, 3, 5, 8, 9])

Is there a better way of doing this?

like image 792
atomh33ls Avatar asked Mar 17 '23 06:03

atomh33ls


1 Answers

You can use numpy.diff with numpy.where:

>>> arr = np.array([1, 5, 6, 7, 7, 8, 8, 0, 2, 7])
>>> np.where(np.diff(arr) > 0)[0] + 1
array([1, 2, 3, 5, 8, 9])
like image 184
Ashwini Chaudhary Avatar answered Mar 23 '23 10:03

Ashwini Chaudhary