Search code examples
python-3.xnumpyarray-broadcasting

Compare two elements of the same Numpy array through broadcasting


I have a numpy array of 2000 elements and I want to find out the indexes in which the element minus the next element divided by itself is bigger than x.

Something like:

a[abs(a[i] - a[i+1])/a[i+1] > x]

I am looking for a way to do this by broadcasting instead of a for loop.


Solution

  • You can use slicing. Start with the array including all but the last value (because the last one has no next value to compare it to), and index it with a Boolean expression: The same array, minus the shifted array starting at index 1, and divided by the shifted array. These operations will all happen element-wise in NumPy. Comparing with x gives the Boolean array that can be used as a filter:

    a[:-1][np.abs(a[:-1] - a[1:]) / a[1:] > x]