在Pandas数据帧中存储FFT周期时出现奇怪的问题 [英] Strange issue when storing FFT periods in Pandas dataframe
问题描述
我正在尝试将FFT计算的结果存储在Pandas数据框中:
I am trying to store the results of FFT calculations in a Pandas data frame:
ft = pd.DataFrame(index=range(90))
ft['y'] = ft.index.map(lambda x: np.sin(2*x))
ft['spectrum'] = np.fft.fft(ft['y'])
ft['freq'] = np.fft.fftfreq(len(ft.index)).real
ft['T'] = ft['freq'].apply(lambda f: 1/f if f != 0 else 0)
一切似乎都工作到最后一行:由于某些原因,应该存储周期的T列具有该帧的所有列,即:
Everything seems to be working fine until the last line: the column T which is supposed to store periods has for some reason all the columns of the frame, ie.:
In [499]: ft.T[0]
Out[499]:
y 0j
spectrum (0.913756021471+0j)
freq 0j
T 0j
Name: 0, dtype: complex128
我不知道为什么.当我只使用freq的真实部分时,也会发生这种情况:
I cannot figure out why is that. It happens also when I only take the real part of freq:
ft['freq'] = np.fft.fftfreq(len(ft.index)).real
或者我尝试使用其他方式来计算T值,例如:
or I try to calculate T values using alternative ways, such as:
ft.T = ft.index.map(lambda i: 1/ft.freq[i] if ft.freq[i] else np.inf)
ft.T = 1/ft.freq
当我对它们运行 head()
或 describe()
时,所有其他列看起来都很整洁,无论它们包含实数值还是复数值.freq列看起来像普通的一维序列,因为 np.fft.fftfreq()
返回一维复数数组,那么列T如此混乱的原因可能是什么?
All other columns look tidy when I run head()
or describe()
on them no matter if they contain real or complex values. The freq column looks like a normal 1D series, because np.fft.fftfreq()
returns 1D array of complex numbers, so what could be the reason why the column T is so messed up?
我正在使用Pandas v.1.19.2和Numpy v.1.12.0.
I am using Pandas v. 1.19.2 and Numpy v. 1.12.0.
推荐答案
熊猫 DataFrame
对象具有 T ,则一切都会按预期进行.
Pandas DataFrame
objects have a property called T
, which is used "to transpose index and columns" of the DataFrame object. If you use a different column name instead of T
, everything works as expected.
这篇关于在Pandas数据帧中存储FFT周期时出现奇怪的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!