9951 explained code solutions for 126 technologies


python-scipyHow can I use Python and SciPy to create a low pass filter?


In order to create a low pass filter using Python and SciPy, the following steps should be taken:

  1. Import the necessary libraries:
import numpy as np
from scipy import signal
  1. Create the low-pass filter. This can be done by using the signal.butter function, which takes three parameters:
    • N: The order of the filter
    • Wn: The cutoff frequency of the filter, normalized from 0 to 1 (1 being the Nyquist frequency)
    • btype: The type of filter, in this case ‘lowpass’
b, a = signal.butter(N=4, Wn=0.2, btype='lowpass')
  1. Use the filter to filter a signal. This can be done by using the signal.lfilter function, which takes three parameters:
    • b: The numerator coefficient array of the filter
    • a: The denominator coefficient array of the filter
    • x: The signal to be filtered
x = np.linspace(0, 10, num=1000)
y = signal.lfilter(b, a, x)
  1. Plot the filtered signal. This can be done by using the matplotlib.pyplot library:
import matplotlib.pyplot as plt

plt.plot(x, y)
plt.show()

Helpful links

Edit this code on GitHub