How to Use SciPy for Signal Processing: Simple Guide
Use
scipy.signal module to perform signal processing tasks such as filtering, Fourier transforms, and peak detection. Import functions like butter for filters or find_peaks for peak detection, then apply them to your data arrays.Syntax
The scipy.signal module provides many functions for signal processing. Common functions include:
butter(N, Wn, btype='low'): Creates a Butterworth filter of orderNwith cutoff frequencyWnnormalized to the Nyquist frequency.lfilter(b, a, x): Applies a linear filter defined by coefficientsbandato signalx.find_peaks(x): Finds peaks in the signalx.fft(x): Computes the Fast Fourier Transform ofx.
These functions work on arrays representing your signal data.
python
from scipy.signal import butter, lfilter, find_peaks from scipy.fft import fft # Butterworth filter design b, a = butter(N=3, Wn=0.1, btype='low') # Apply filter to data filtered_signal = lfilter(b, a, [1, 2, 3, 4, 5]) # Find peaks peaks, _ = find_peaks([0, 2, 1, 3, 0]) # Compute FFT signal_fft = fft([1, 2, 3, 4])
Example
This example shows how to create a low-pass Butterworth filter, apply it to a noisy signal, and detect peaks in the filtered signal.
python
import numpy as np import matplotlib.pyplot as plt from scipy.signal import butter, lfilter, find_peaks # Create sample data: noisy sine wave fs = 100 # Sampling frequency T = 1.0 # seconds n = int(T * fs) # number of samples t = np.linspace(0, T, n, endpoint=False) signal = np.sin(2 * np.pi * 5 * t) + 0.5 * np.random.randn(n) # Design Butterworth low-pass filter order = 4 cutoff = 10 # cutoff frequency in Hz b, a = butter(order, cutoff / (0.5 * fs), btype='low') # Apply filter filtered_signal = lfilter(b, a, signal) # Find peaks in filtered signal peaks, _ = find_peaks(filtered_signal, height=0) # Plot results plt.figure(figsize=(10, 6)) plt.plot(t, signal, label='Noisy signal') plt.plot(t, filtered_signal, label='Filtered signal', linewidth=2) plt.plot(t[peaks], filtered_signal[peaks], 'ro', label='Peaks') plt.xlabel('Time [seconds]') plt.ylabel('Amplitude') plt.legend() plt.title('Signal Filtering and Peak Detection with SciPy') plt.show()
Output
A plot window showing a noisy sine wave, its filtered version, and red dots marking detected peaks on the filtered signal.
Common Pitfalls
Common mistakes when using SciPy for signal processing include:
- Not normalizing the cutoff frequency by the Nyquist frequency (half the sampling rate) when designing filters.
- Applying filters without considering signal edge effects, which can cause distortions.
- Using
find_peakswithout setting parameters likeheightordistance, leading to false peak detections. - Confusing
scipy.fftwithnumpy.fft; SciPy's FFT is recommended for newer code.
Example of wrong and right filter design:
python
# Wrong: cutoff frequency not normalized from scipy.signal import butter fs = 100 cutoff = 10 # Incorrect: cutoff not divided by Nyquist frequency # b, a = butter(3, cutoff, btype='low') # This will cause an error or wrong filter # Right: normalize cutoff frequency b, a = butter(3, cutoff / (0.5 * fs), btype='low')
Quick Reference
Here is a quick summary of useful SciPy signal processing functions:
| Function | Purpose | Key Parameters |
|---|---|---|
| butter | Design Butterworth filter | N (order), Wn (cutoff freq), btype ('low', 'high') |
| lfilter | Apply linear filter | b, a (filter coeffs), x (signal) |
| find_peaks | Detect peaks in signal | height, distance, prominence |
| fft | Compute Fast Fourier Transform | x (signal array) |
| freqz | Frequency response of filter | b, a (filter coeffs) |
Key Takeaways
Use scipy.signal module functions like butter and lfilter for filtering signals.
Always normalize cutoff frequencies by Nyquist frequency when designing filters.
Use find_peaks with parameters to accurately detect signal peaks.
Apply FFT with scipy.fft for frequency analysis of signals.
Visualize signals before and after processing to verify results.