2011-12-06 45 views
2

我对python和编程还很新,我试图弄清楚我是否以正确的方式解决这个问题。我往往有一个matlab办法的事情,但在这里我只是挣扎...反向阵列元素评估

语境: 我有两个numpy的阵列中this image on flickr绘制的,因为我不能在这里张贴的照片:(他们是等长的。属性(都是777x1600),我尝试使用红色数组来帮助返回箭头指示的蓝色曲线中的点的索引(图的x轴上的值)和元素值(y轴) 。蓝色阵列的每一行

我一直在负责该过程是: a)决定红色阵列的最大值(表示与图红点和已实现)

和b)从最后一个元素开始到蓝色数组的末尾,向后计数,比较元素和前一个元素。目标是确定前一个值下降的位置。 (例如,当元素-1大于元素-2时,表示图像中的最后一个峰值)。此外,为了防止在值增大的部分尾部选择“噪声”,我还需要将选定值限制为大于红色数组的最大值。

这是我到目前为止,但我卡在第二行,我必须评估从该行中的(-1)位置的数组的选定行到开始,或(0)位置:

for i,n in enumerate(blue): #select each row of blue in turn to analyze 
    for j,m in enumerate(n): #select each element of blue ??how do I start from the end of array and work backwards?? 
     if m > m-1 and m > max_val_red[i]: 
     indx_m[i] = j 
     val_m[i] = m 
+0

enumerate(n [:: - 1])可以工作... 该列表将被逆转,但索引将从0开始到n – avasal

回答

0

对不起,我没有阅读全部内容,但可以查看内置函数的反转。 因此而不是枚举(n)。你可以做倒转(枚举(n))。但是,那么你的索引将是错误的正确的索引将评估len(n) - j

2

要直接回答您的问题,您可以使用n [:: - 1]来反转arrray n。

因此,代码为:

for j, m in enumerate(n[::-1]): 
    j = len(n)-j-1 
    # here is your code 

但增加计算速度,你应该避免蟒蛇循环:

import numpy as np 
n = np.array([1,2,3,4,2,5,7,8,3,2,3,3,0,1,1,2]) 

idx = np.nonzero(np.diff(n) < 0)[0] 
peaks = n[idx] 
mask = peaks > 3 # peak muse larger than 3 

print "index=", idx[mask] 
print "value=", peaks[mask] 

输出为:

index= [3 7] 
value= [4 8] 
+0

谢谢您的建议,并且我会在截止日期不再来时提醒您。非常感激。 –

1

我假定你的意思:

if m > n[j-1] and m > max_val_red[i]: 
    indx_m[i] = j 
    val_m[i] = m 

因为m > m - 1总是真

要反转的轴线上你可以索引该轴上使用::-1阵列,例如以反向于轴线1蓝色可以使用一个阵列:

blue_reverse = blue[:, ::-1] 

试着看看你可以将你的函数写成一组数组操作而不是循环(这往往会更快)。这与其他答案类似,但它应该允许您避免当前正在使用的两个循环:

threshold = red.max(1) 
threshold = threshold[:, np.newaxis] #this makes threshold's shape (n, 1) 

blue = blue[:, ::-1] 
index_from_end = np.argmax((blue[:, :-1] > blue[:, 1:]) & (blue[:, :-1] > threshold), 1) 
value = blue[range(len(blue)), index_from_end] 
index = blue.shape[1] - 1 - index_from_end