Skip to content Skip to sidebar Skip to footer

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 th

Solution 1:

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

Solution 2:

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.

Post a Comment for "Get Indices Of Numpy 1d Array Where Value Is Greater Than Previous Element"