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?
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With