Search code examples
pythonnumpyfilterscipysignal-processing

Error with Padlen in signal.filtfilt in Python


I am working with library "scipy.signal" in Python and I have the next code:

from scipy import signal

b = [ 0.001016    0.00507999  0.01015998  0.01015998  0.00507999  0.001016  ]

a = [ 1.         -3.0820186   4.04351697 -2.76126457  0.97291013 -0.14063199]
data = [[ 1.]
[ 1.]
[ 1.]
...]
# length = 264
y = signal.filtfilt(b, a, data)

But when I execute the code I get the next error message:

The length of the input vector x must be at least padlen, which is 18.

What could I do?


Solution

  • It appears that data is a two-dimensional array with shape (264, 1). By default, filtfilt filters along the last axis of the input array, so in your case it is trying to filter along an axis where the length of the data is 1, which is not long enough for the default padding method.

    I assume you meant to interpret data as a one-dimensional array. You can add the argument axis=0

    y = signal.filtfilt(b, a, data, axis=0)
    

    to filter along the first dimension (i.e. down the column), in which case the output y will also have shape (264, 1). Alternatively, you can convert the input to a one-dimensional array by flattening it with np.ravel(data) or by using indexing to select the first (and only) column, data[:, 0]. (The latter will only work if data is, in fact, a numpy array and not a list of lists.) E.g.

    y = signal.filtfilt(b, a, np.ravel(data))
    

    In that case, the output y will also be a one-dimensional array, with shape (264,).