Strange issue when storing FFT periods in Pandas dataframe

白昼怎懂夜的黑 提交于 2021-02-10 19:57:51

问题


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)

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

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

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

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?

I am using Pandas v. 1.19.2 and Numpy v. 1.12.0.


回答1:


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.



来源:https://stackoverflow.com/questions/42923343/strange-issue-when-storing-fft-periods-in-pandas-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!