BDP
BDP

Reputation: 291

Finding the index values where a certain value occurs in an array in Python

I am using a DAQ to sample a voltage which is sinusoidal. I am storing the samples in a list, then taking the FFT of that list. My problem is that I only want to take the FFT of complete periods of the sine wave, so I want to find the index values of the list where the values are very close to zero so that I can change the other values to zero.

For example, if I had a very crude sine wave sampled as:

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

I would want to detect the zeros (really every other zero) so that I can make the array:

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

One other thing is that since there is noise and my sampling frequency isn't infinitely large, I won't get values that are exactly zero. Therefore, I would need to look for values in a range such as in range(-0.1,0.1).

I looked at the numpy library and numpy.where() looked like it might be the right tool, but I'm having issues implementing it. I am an EE and have little programming experience, so any help is very appreciated!

Upvotes: 3

Views: 1360

Answers (2)

BDP
BDP

Reputation: 291

Your answer was extremely helpful kirelagin, but I had issues with the part where you set the values to 0. I am not very experienced in Python, but it seems to me that you can not populate an array with an equal sign like you can in some languages. Instead I ended up doing something like this:

    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)

The insert function adds 0's to the beginning of the array, and append adds 0's to the end of the array. This solution works perfectly fine for me, even though I'm sure there is a much more elegant way to replace values in an array with a different value which I do not know about.

Upvotes: 0

kirelagin
kirelagin

Reputation: 13626

>>> 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])

Upvotes: 3

Related Questions