指数衰减正弦函数的FFT



我有一组仿真数据,我想对这些数据执行FFT。我正在使用matplotlib来做到这一点。但是,FFT 看起来很奇怪,所以我不知道我的代码中是否缺少某些内容。将不胜感激任何帮助。

原始数据:

时变数据

FFT:

FFT

FFT 计算代码:

import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack as fftpack
data = pd.read_csv('table.txt',header=0,sep="t")
fig, ax = plt.subplots()
mz_res=data[['mz ()']].to_numpy()
time=data[['# t (s)']].to_numpy()
ax.plot(time[:300],mz_res[:300])
ax.set_title("Time-varying mz component")
ax.set_xlabel('time')
ax.set_ylabel('mz amplitude')
fft_res=fftpack.fft(mz_res[:300])   
power=np.abs(fft_res)
frequencies=fftpack.fftfreq(fft_res.size)
fig2, ax_fft=plt.subplots()
ax_fft.plot(frequencies[:150],power[:150]) // taking just half of the frequency range

我只是绘制前 300 个数据点,因为其余的并不重要。

我在这里做错了什么吗?我期待的是单频峰值,而不是我得到的。谢谢!

输入文件的链接:

帕斯宾

编辑

事实证明,错误在于将数据帧转换为 numpy 数组。出于我尚未理解的原因,如果我将数据帧转换为 numpy 数组,它将转换为数组数组,即结果数组的每个元素本身都是单个元素的数组。当我将代码更改为:

mz_res=data['mz ()'].to_numpy()

因此,它是从熊猫系列到 numpy 数组的转换,然后 FFT 的行为符合预期,我从 FFT 获得单频峰值。

所以我把它放在这里,以防其他人觉得它有用。经验教训:从熊猫系列转换为 numpy 数组会产生与从熊猫数据帧转换不同的结果。

解决方案:

使用从熊猫系列到 numpy 数组的转换,而不是从熊猫数据帧到 numpy 数组。

法典:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack as fftpack
data = pd.read_csv('table.txt',header=0,sep="t")
fig, ax = plt.subplots()
mz_res=data['mz ()'].to_numpy()  #series to array
time=data[['# t (s)']].to_numpy()   #dataframe to array
ax.plot(time,mz_res)
ax.set_title("Time-varying mz component")
ax.set_xlabel('time')
ax.set_ylabel('mz amplitude')
fft_res=fftpack.fft(mz_res)   
power=np.abs(fft_res)
frequencies=fftpack.fftfreq(fft_res.size)
indices=np.where(frequencies>0)
freq_pos=frequencies[indices]
power_pos=power[indices]
fig2, ax_fft=plt.subplots()
ax_fft.plot(freq_pos,power_pos) # taking just half of the frequency range
ax_fft.set_title("FFT")
ax_fft.set_xlabel('Frequency (Hz)')
ax_fft.set_ylabel('FFT Amplitude')
ax_fft.set_yscale('linear')

收益 率:

时间依赖性

FFT

最新更新