Reputation: 450
I have a 1D array and I want to compare two sibling elements where the condition where element is greater than a threshold and previous element is less than or equal to threshold. I have a the current solution that loops thru the array comparing which element. Here is a simple example:
t = np.array([1,2,2,2,2,3,5,4,5,3,4,5,6,8,9,7,8,9,10])
threshold = 5
target_index = -1
for index in range(1, len(t)):
if t[index] > threshold and t[index-1] <= threshold
target_index = index
break
I am trying to figure out if there was some type of fancy indexing solution or a faster way of doing this.
Upvotes: 0
Views: 163
Reputation: 4199
I use roll, logical_and and where to get the index with the desired condition.
t = np.array([1,2,2,2,2,3,5,4,5,3,4,5,6,8,9,7,8,9,10])
threshold = 5
from numpy import logical_and, roll, where
def ops_func(t, threshold):
target_index = -1
for index in range(1, len(t)):
if (t[index] > threshold) and (t[index-1] <= threshold) :
target_index = index
break
return target_index
def myfunc(t, threshold):
return where(logical_and(t>threshold,roll(t,1)<=threshold))
print ops_func(t,threshold)
# lists the first index which satisfy the desired condition
print ops_func(t,threshold=3)
print myfunc(t, threshold)
# lists all the indices which satisfy the desired condition
print myfunc(t, threshold=3)
%timeit myfunc
%timeit ops_func
results in
12
6
(array([12], dtype=int64),)
(array([ 6, 10], dtype=int64),)
10000000 loops, best of 3: 23.3 ns per loop
100000000 loops, best of 3: 19.5 ns per loop
Upvotes: 1