How to extract frequency associated with fft values in Python?
In this article, we will find out the extract the values of frequency from an FFT. We can obtain the magnitude of frequency from a set of complex numbers obtained after performing FFT i.e Fast Fourier Transform in Python. The frequency can be obtained by calculating the magnitude of the complex number. So simple ab(x) on each of those complex numbers should return the frequency.
In order to extract frequency associated with fft values we will be using the fft.fft() and fft.fftfreq() methods of numpy module.
- numpy.fft.fft(): It calculates the single-dimensional n-point DFT i.e. Discrete Fourier Transform with an optimized FFT i.e Fast Fourier Transform algorithm.
Syntax: numpy.fft.fft(a, axis=-1)
- a: Input array can be complex.
- axis: Axis over which to compute the FFT. If not given, the last axis is used.
Returns: The truncated or zero-padded input, transformed along the axis indicated by axis, or the last one if the axis is not specified.
- numpy.fft.fftfreq(): It computes the frequencies associated with the coefficients.
Syntax: numpy.fft.fftfreq(n, d=1.0)
- n: Window length.
- d: Sample spacing (inverse of the sampling rate). Defaults to 1.
Returns: Array of length n containing the sample frequencies.
Step 1: Import required modules.
Step 2: Create an array using a NumPy.
Step 3: A signal x defined in the time domain of length N, sampled at a constant interval dt, its DFT W(here specifically W = np.fft.fft(x)), whose elements are sampled on the frequency axis with a sample rate dw. (A DFT converts a list of N complex numbers to a list of N complex numbers)
Step 4: The np.fft.fftfreq() method tells you the frequencies associated with the coefficients.
Step 5: Extract frequency associated with fft values.
Below is the complete program based in the above approach:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course