2017-03-25 56 views
0

我有一個一維數組,我想比較兩個同級元素,其中其中元素比和前一個元素越大條件是小於或等於閾值。我有一個當前的解決方案,通過數組來比較哪個元素。下面是一個簡單的例子:numpy的索引比較兩個元件

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 

我試圖找出是否有某種類型的索引看中的解決辦法或這樣做的更快的方法。

回答

1

我使用roll,logical_and和where索引以及所需的條件。

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 

導致

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 
+0

該溶液仍然比天然蟒功能慢。 – kmario23

+0

@ kmario23感謝您的評論。通過本地python函數,你的意思是OP發佈的函數嗎? – plasmon360

+0

是的。我的機器慢了4倍。請用'timeit'驗證它 – kmario23