Home > Enterprise >  Accessing indices in an array where the elements value difference occurs
Accessing indices in an array where the elements value difference occurs

Time:07-22

I have a one dimensional list like :

val=np.array([1,1,0,0,1,1,0,4,0,0,1])

My requirement is to access the indices, where the difference between element is 1(like the transition occurs from 1 to 0 and 0 to 1 in that point the value difference is -1,1 respectively).

I tried with this function. some how,I am able to get the desired out put.

val=np.array([1,1,0,0,1,1,0,4,0,0,1])

result_1 = [(i, i   1)for i in np.where(np.diff(val) ==1 )[0]]
result_2=[(i, i   1)for i in np.where(np.diff(val) ==-1)[0]]

Received output:

[(3, 4), (9, 10)]
[(1, 2), (5, 6)]

Again,I tried again with and function

result_1 = [(i, i   1)for i in np.where(np.diff((val) ==1 & (val) ==1 ))[0]] 

I received an error like this

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() 
or a.all()

Expected output:

[(1,2),(3, 4),(5,6) (9, 10)]

CodePudding user response:

Compare against the absolute value (using numpy.abs) to combine both results:

import numpy as np

val = np.array([1, 1, 0, 0, 1, 1, 0, 4, 0, 0, 1])

result = [(i, i   1) for i in np.where(np.abs(np.diff(val)) == 1)[0]]
print(result)

Output

[(1, 2), (3, 4), (5, 6), (9, 10)]
  • Related