How to get the Fourier series using Python's $\tt fft$ I Would like to be able to reconstruct every individual sinusoid that makes up a Discrete signal. I Have the following signal: (I am working in Python)


The signal is essentially an array with about 400 elements that varies with time. In Python after calling the fft function on the data 

 dft= rfft(dat)/len(dat)  #real fft


I receive the figure below:


I am aware that I can use the result of the fft to obtain the individual Fourier series components, but I am unsure exactly how. The code I have yields me an array of magnitudes for each harmonic of the signal, how do I use that to get each individual component of the Fourier series?
I am no expert in this topic, but have some useful examples to share.

1 component example

To keep the i-eth Fourier component, you can zero the rest of the components:

n = len(y)
Y = numpy.fft.fft(y)
numpy.put(Y, range(0, i), 0.0)
numpy.put(Y, range(i+1, n), 0.0)
# Now Y holds 1 imaginary coefficient corresponding with the i-eth Fourier component


If you're looking for the Real signal corresponding to the chosen i-eth component, you can afterwards perform the inverse transform through ifft:

ifft = numpy.fft.ifft(Y) # the sinusoid you're looking for


Multiple components example

The more Fourier components you keep, the closer you'll mimic the original signal. This example shows what happens when you keep 10, 20, ...up tp n components. 

Assuming x and y are your data vectors.

import numpy
from matplotlib import pyplot as plt

n = len(y)
COMPONENTS = [10, 20, n]

for c in COMPONENTS:
    colors = numpy.linspace(start=100, stop=255, num=c)
    for i in range(c):
        Y = numpy.fft.fft(y)
        numpy.put(Y, range(i+1, n), 0.0)
        ifft = numpy.fft.ifft(Y)
        plt.plot(x, ifft, color=plt.cm.Reds(int(colors[i])), alpha=.70)

    plt.title("First {c} fourier components".format(c=c))
    plt.plot(x,y, label="Original dataset")
    plt.grid(linestyle='dashed')
    plt.legend()
    plt.show()






...see how it mimics the original signal?