0
0
SciPydata~5 mins

Applying filters (lfilter, sosfilt) in SciPy

Choose your learning style9 modes available
Introduction

Filters help clean or change signals by removing noise or unwanted parts. Using lfilter and sosfilt lets us apply these filters easily to data.

You want to remove background noise from a sound recording.
You need to smooth sensor data to see trends better.
You want to isolate a specific frequency range in a signal.
You are processing EEG or heart rate signals to remove interference.
Syntax
SciPy
from scipy.signal import lfilter, sosfilt

# lfilter syntax:
y = lfilter(b, a, x)

# sosfilt syntax:
y = sosfilt(sos, x)

lfilter uses filter coefficients b and a to process the input x.

sosfilt uses a second-order sections array sos which is more stable for complex filters.

Examples
This applies a simple moving average filter to smooth the data.
SciPy
from scipy.signal import lfilter
b = [0.2, 0.2, 0.2, 0.2, 0.2]
a = [1]
x = [1, 2, 3, 4, 5]
y = lfilter(b, a, x)
print(y)
This applies a Butterworth low-pass filter using second-order sections.
SciPy
from scipy.signal import butter, sosfilt
sos = butter(4, 0.3, output='sos')
x = [1, 2, 3, 4, 5]
y = sosfilt(sos, x)
print(y)
Sample Program

This program creates a noisy sine wave and cleans it using two filtering methods: lfilter and sosfilt. It prints the first five values of the original and filtered signals to compare.

SciPy
import numpy as np
from scipy.signal import lfilter, butter, sosfilt

# Create a noisy signal
np.random.seed(0)
time = np.linspace(0, 1, 100)
signal = np.sin(2 * np.pi * 5 * time) + 0.5 * np.random.randn(100)

# Design a Butterworth low-pass filter
b, a = butter(4, 0.1)
sos = butter(4, 0.1, output='sos')

# Filter the signal using lfilter
filtered_lfilter = lfilter(b, a, signal)

# Filter the signal using sosfilt
filtered_sosfilt = sosfilt(sos, signal)

# Print first 5 values of original and filtered signals
print('Original signal (first 5):', signal[:5])
print('Filtered with lfilter (first 5):', filtered_lfilter[:5])
print('Filtered with sosfilt (first 5):', filtered_sosfilt[:5])
OutputSuccess
Important Notes

lfilter can be less stable for high-order filters; sosfilt is better for those cases.

Always check the filter design to match your signal's needs (cutoff frequency, order).

Input signal x can be a list or numpy array.

Summary

Filters help clean or shape signals by removing unwanted parts.

lfilter uses numerator and denominator coefficients to apply filters.

sosfilt uses second-order sections for more stable filtering, especially for complex filters.