TExcelTAD
Home › SciPy › SciPy Signal Filters

SciPy Signal Filters

A signal is any quantity measured over time: audio, heart rate, vibration, stock prices, sensor readings. Real signals are mixed with things you don't want — electrical hum, random noise, slow drift. A filter keeps the parts you want and removes the rest. The scipy.signal module can design filters and apply them.

Smoothing with a moving average

The simplest filter averages each sample with its neighbours. Here a slow 1 Hz wave sampled at 100 Hz is buried in noise; averaging 9 samples at a time cleans it up:

python · try it yourself
import numpy as np
from scipy import signal

rng = np.random.default_rng(0)
fs = 100                                   # samples per second
t = np.arange(0, 2, 1 / fs)
clean = np.sin(2 * np.pi * 1 * t)
noisy = clean + rng.normal(0, 0.4, t.size)

window = np.ones(9) / 9
smoothed = signal.convolve(noisy, window, mode="same")

def rms(x):
    return np.sqrt(np.mean(x ** 2))

inner = slice(10, -10)                     # ignore the edges
print(f"error before: {rms(noisy - clean)[()]:.3f}")
print(f"error after : {rms((smoothed - clean)[inner]):.3f}")
error before: 0.385
error after : 0.149

A moving average is a crude low-pass filter: it lets slow changes through and suppresses fast ones.

Filter types

Type Keeps Removes Example use
Low-pass frequencies below a cutoff fast noise smoothing sensor data
High-pass frequencies above a cutoff slow drift, offset removing baseline wander from an ECG
Band-pass a range of frequencies everything outside isolating a voice or a tone
Band-stop (notch) everything except a range one narrow frequency removing 50/60 Hz mains hum

Frequencies are measured in hertz (Hz, cycles per second). The highest frequency a sampled signal can represent is half the sampling rate — the Nyquist frequency.

Designing a Butterworth filter

The Butterworth filter is the usual first choice: its passband is as flat as possible. signal.butter(order, cutoff, btype, fs=...) designs it. Use the output="sos" form (second-order sections), which is numerically robust, and apply it with sosfiltfilt, which runs the filter forwards and backwards so the output isn't delayed:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal

rng = np.random.default_rng(1)
fs = 200
t = np.arange(0, 2, 1 / fs)
slow = np.sin(2 * np.pi * 2 * t)                      # 2 Hz signal we want
fast = 0.5 * np.sin(2 * np.pi * 40 * t)               # 40 Hz interference
x = slow + fast + rng.normal(0, 0.2, t.size)

sos = signal.butter(4, 10, btype="lowpass", fs=fs, output="sos")
y = signal.sosfiltfilt(sos, x)

plt.plot(t, x, alpha=0.5, label="raw")
plt.plot(t, y, lw=2, label="low-pass 10 Hz")
plt.plot(t, slow, "k--", label="true 2 Hz signal")
plt.xlabel("time (s)")
plt.legend()
plt.show()
print(f"max deviation from the 2 Hz signal: raw {np.abs(x - slow).max():.2f}, "
      f"filtered {np.abs(y - slow).max():.2f}")
max deviation from the 2 Hz signal: raw 1.02, filtered 0.31

Frequency response

How much does a filter let through at each frequency? sosfreqz computes the frequency response. The gain is 1 (0 dB) in the passband, about 0.707 (−3 dB) at the cutoff, and falls off beyond it — faster for higher orders:

python · try it yourself
import numpy as np
from scipy import signal

fs = 200
freqs = [2, 10, 20, 40]
for order in (2, 6):
    sos = signal.butter(order, 10, fs=fs, output="sos")
    w, h = signal.sosfreqz(sos, worN=freqs, fs=fs)
    gains = ", ".join(f"{f} Hz: {abs(g):.3f}" for f, g in zip(w, h))
    print(f"order {order}: {gains}")
order 2: 2.0 Hz: 0.999, 10.0 Hz: 0.707, 20.0 Hz: 0.231, 40.0 Hz: 0.047
order 6: 2.0 Hz: 1.000, 10.0 Hz: 0.707, 20.0 Hz: 0.013, 40.0 Hz: 0.000

High-pass and band-stop filters

A high-pass filter removes slow drift; a notch filter (iirnotch) removes one narrow frequency such as mains hum:

python · try it yourself
import numpy as np
from scipy import signal

fs = 500
t = np.arange(0, 4, 1 / fs)
beat = np.sin(2 * np.pi * 1.2 * t)             # 1.2 Hz "heartbeat"
drift = 0.8 * t / 4                            # slow upward drift
hum = 0.3 * np.sin(2 * np.pi * 50 * t)         # 50 Hz mains hum
x = beat + drift + hum

hp = signal.butter(2, 0.5, btype="highpass", fs=fs, output="sos")
b, a = signal.iirnotch(50, Q=30, fs=fs)
y = signal.filtfilt(b, a, signal.sosfiltfilt(hp, x))

core = slice(500, -500)                        # skip 1 s at each edge
print(f"mean level   : raw {x[core].mean():.3f}, cleaned {y[core].mean():.3f}")
print(f"error vs beat: raw {np.abs(x - beat)[core].max():.3f}, "
      f"cleaned {np.abs(y - beat)[core].max():.3f}")
mean level   : raw 0.475, cleaned 0.054
error vs beat: raw 0.883, cleaned 0.145

Median filter for spikes

Linear filters smear short spikes instead of removing them. A median filter replaces each sample with the median of its neighbours, which deletes isolated spikes while keeping sharp edges:

python · try it yourself
import numpy as np
from scipy import signal

x = np.array([1, 1, 1, 9, 1, 1, 5, 5, 5, -7, 5, 5], dtype=float)
print("signal  :", x)
print("median 3:", signal.medfilt(x, kernel_size=3))
print("mean 3  :", np.round(np.convolve(x, np.ones(3) / 3, mode="same"), 2))
signal  : [ 1.  1.  1.  9.  1.  1.  5.  5.  5. -7.  5.  5.]
median 3: [1. 1. 1. 1. 1. 1. 5. 5. 5. 5. 5. 5.]
mean 3  : [0.67 1.   3.67 3.67 3.67 2.33 3.67 5.   1.   1.   1.   3.33]

Tip: Use sosfiltfilt/filtfilt for recorded data (no delay, but needs the whole signal). For real-time processing, where future samples aren't available yet, use sosfilt and accept a small delay.

Test yourself

Which filter type removes slow drift while keeping faster changes?

  1. Low-pass
  2. High-pass
  3. Moving average
  4. Median

What is the Nyquist frequency of a signal sampled at 200 Hz?

  1. 50 Hz
  2. 100 Hz
  3. 200 Hz
  4. 400 Hz

Why use sosfiltfilt instead of sosfilt on recorded data?

  1. It is a different filter type
  2. It runs forwards and backwards, so the output has no time delay
  3. It only works on images
  4. It increases the noise