查找Python中数组中某个值出现的索引值

时间:2013-06-12 23:57:38

标签: python python-2.7 numpy

我正在使用DAQ来采样正弦电压。我将样本存储在列表中,然后采用该列表的FFT。我的问题是我只想对正弦波的完整周期进行FFT,所以我想找到值非常接近于零的列表的索引值,这样我就可以将其他值更改为零。 / p>

例如,如果我有一个非常粗糙的正弦波采样为:

[-3, -2, -1, 0, 1, 2, 3, 4, 3, 2, 1, 0, -1, -2, -3,  4, -3, -2, -1, 0, 1, 2]

我想检测零(实际上每隔一个零)以便我可以制作数组:

[ 0,  0,  0, 0, 1, 2, 3, 4, 3, 2, 1, 0, -1, -2, -3, -4, -3, -2, -1, 0, 0, 0]

另一件事是,由于存在噪声且我的采样频率不是无限大,我不会得到正好为零的值。因此,我需要查找范围(-0.1,0.1)范围内的值。

我查看了numpy库和numpy.where()看起来它可能是正确的工具,但我遇到了实现它的问题。我是一名EE,并且几乎没有编程经验,所以非常感谢任何帮助!

2 个答案:

答案 0 :(得分:3)

>>> l = np.array([-3, -2, -1, 0, 1, 2, 3, 4, 3, 2, 1, 0, -1, -2, -3, 4, -3, -2, -1, 0, 1, 2])
>>> epsilon = 1
>>> inds = np.argwhere(np.abs(l) < epsilon) # indices of “almost zero” items
>>> left = inds[0] # index of the first “almost zero” value
>>> right = inds[-1] # -//- last
>>> l[:left + 1] = 0 # zero out everything to the left and including the first “almost zero”
>>> l[right:] = 0 # -//- last
>>> l
  >
array([ 0,  0,  0,  0,  1,  2,  3,  4,  3,  2,  1,  0, -1, -2, -3,  4, -3,
   -2, -1,  0,  0,  0])

答案 1 :(得分:0)

你的答案对kirelagin非常有帮助,但我在将值设置为0的部分遇到了问题。我对Python不是很有经验,但在我看来你不能用类似的符号填充数组你可以用某些语言。相反,我最终做了这样的事情:

    epsilon = 1
    length = len(l)
    inds = np.argwhere(np.abs(l)<epsilon)
    left = inds[0]
    right = inds[-1]
    del l[:left]
    del l[right-left+1:]
    for x in range (0,left):
        l.insert(x,0)
    endzeros = length - right -1
    for x in range (0, endzeros):
        l.append(0)

insert函数将0添加到数组的开头,append将0添加到数组的末尾。这个解决方案对我来说非常合适,尽管我确信有一种更优雅的方法可以用不同的值替换数组中的值。