Lee
Lee

Reputation: 31040

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?

Upvotes: 5

Views: 4188

Answers (2)

Kersten
Kersten

Reputation: 984

An alternative would be to use array slicing:

>>> arr = np.array([1, 5, 6, 7, 7, 8, 8, 0, 2, 7])
>>> np.where(np.r_[False, arr[1:] > arr[:-1]])[0]
array([1, 2, 3, 5, 8, 9])

You shift the array one to the right and compare it with itself. The length of the result is shorter than the original array. Since the first value can not be compared with one to it's left you set the first result to false.

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

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])

Upvotes: 8

Related Questions