Home > Software design >  Add width to a numpy 1d "signal array "
Add width to a numpy 1d "signal array "

Time:11-19

I have a numpy int 1D array. Which looks like this:

[0,0,0,0,0,1,0,0,0,0,2,0,0,0,0,5,0,0,0,1,0,0,0,0,0,0,0,0,0,0]

Basically, it's an array of mostly zeros with some signals that are ints [1,2,3,4,5,...] and the signals always have a "width" of 1, meaning they are surrounded by 0s.

I want to add "width" to each signal so instead of taking only 1 space in the array it would take width space in the array. So, in this example with the width of 3, I would get

[0,0,0,0,1,1,1,0,0,2,2,2,0,0,5,5,5,0,1,1,1,0,0,0,0,0,0,0,0,0]

The length of the array stays the same, the width can be 3,5,7, but nothing too outrageous.

What would be the fastest way to do this? I feel like there probably is an easy way to do this, but not sure how to correctly call this operation.

CodePudding user response:

Convolution might be what you're looking for?

>>> import numpy as np
>>> width = 3
>>> a = np.array([0,0,0,0,0,1,0,0,0,0,2,0,0,0,0,5,0,0,0,1,0,0,0,0,0,0,0,0,0,0])
>>> np.convolve(a, np.ones(width))
array([0., 0., 0., 0., 0., 1., 1., 1., 0., 0., 2., 2., 2., 0., 0., 5., 5.,
       5., 0., 1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

This does not preserve the length of the array though. If you want to preserve the length, you should use the 'same' mode as such:

>>> np.convolve(a, np.ones(width), mode='same')
array([0., 0., 0., 0., 1., 1., 1., 0., 0., 2., 2., 2., 0., 0., 5., 5., 5.,
       0., 1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

If this is not fast enough, I suggest you take a look at scipy.signal.fftconvolve.

CodePudding user response:

I know it's not the perfect solution but here it is: I made a duplicate of the intial list and created a width range so when I find a number diffrent than 0 I replace the surrounding zeros with the appropriate number

arr = [0,0,0,0,0,1,0,0,0,0,2,0,0,0,0,5,0,0,0,1,0,0,0,0,0,0,0,0,0,0]
arr1 = [0,0,0,0,0,1,0,0,0,0,2,0,0,0,0,5,0,0,0,1,0,0,0,0,0,0,0,0,0,0]
width = 3
width_range = [i for i in range(width//(-2) 1,width//(2) 1)]
print('width_range: ',width_range)
for idx,elem in enumerate(arr):
    if elem !=0:
        for i in width_range:
            arr1[idx i]=elem
print(arr1)

Output:

width_range:  [-1, 0, 1]
[0, 0, 0, 0, 1, 1, 1, 0, 0, 2, 2, 2, 0, 0, 5, 5, 5, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]

PS: This example only works with 3 and 5 if you want to test it with 7 you need to add zeros between your signals.

  • Related