Band-pass and band-stop filters help us keep or remove specific ranges of signals. This is useful to focus on important parts or remove noise.
Band-pass and band-stop filters in Signal Processing
band_pass_filter(signal, low_cutoff, high_cutoff) band_stop_filter(signal, low_cutoff, high_cutoff)
band_pass_filter keeps frequencies between low_cutoff and high_cutoff.
band_stop_filter removes frequencies between low_cutoff and high_cutoff, keeping others.
filtered_signal = band_pass_filter(signal, 100, 300)
clean_signal = band_stop_filter(signal, 50, 60)
This program creates a signal with two frequencies: 50 Hz and 200 Hz. It then applies a band-pass filter to keep only the 40-60 Hz range and a band-stop filter to remove that same range. The first 5 samples of each result are printed to show the effect.
import numpy as np import matplotlib.pyplot as plt from scipy.signal import butter, filtfilt # Create a sample signal with mixed frequencies fs = 1000 # Sampling frequency in Hz T = 1.0 # seconds n = int(T * fs) t = np.linspace(0, T, n, endpoint=False) # Signal with 50 Hz and 200 Hz components signal = np.sin(2 * np.pi * 50 * t) + 0.5 * np.sin(2 * np.pi * 200 * t) # Define band-pass filter function def band_pass_filter(data, lowcut, highcut, fs, order=4): nyq = 0.5 * fs low = lowcut / nyq high = highcut / nyq b, a = butter(order, [low, high], btype='band') y = filtfilt(b, a, data) return y # Define band-stop filter function def band_stop_filter(data, lowcut, highcut, fs, order=4): nyq = 0.5 * fs low = lowcut / nyq high = highcut / nyq b, a = butter(order, [low, high], btype='bandstop') y = filtfilt(b, a, data) return y # Apply band-pass filter to keep 40-60 Hz bp_filtered = band_pass_filter(signal, 40, 60, fs) # Apply band-stop filter to remove 40-60 Hz bs_filtered = band_stop_filter(signal, 40, 60, fs) # Print first 5 values of each signal print('Original signal samples:', signal[:5]) print('Band-pass filtered samples:', bp_filtered[:5]) print('Band-stop filtered samples:', bs_filtered[:5])
Band-pass filters keep only the frequencies inside the chosen range.
Band-stop filters remove frequencies inside the chosen range and keep others.
Choosing the right cutoff frequencies depends on your signal and what you want to keep or remove.
Band-pass filters keep signals only in a specific frequency range.
Band-stop filters remove signals in a specific frequency range.
These filters help clean or focus on parts of signals in real-world data.