2017-03-25 61 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