Search code examples
pythonpandasnumpyfftvibration

how to calculate dominant frequency use numpy.fft in python


I have this data frame about vehicle vibration and I want to calculate the dominant frequency of the vibration. I know that we can calculate it using numpy.fft, but I have no idea how can I apply numpy.fft to my data frame. Please enlighten me how to do it in python. Thankyou.


Solution

  • A dataframe column is a NumPy array effectively

    df = pd.DataFrame({"Vibration":[random.uniform(2,10) for i in range(10)]})
    df["fft"] = np.fft.fft(df["Vibration"].values)
    print(df.to_string())
    

    output

       Vibration                  fft
    0   8.212039  63.320213+0.000000j
    1   5.590523   2.640720-2.231825j
    2   8.945281  -2.977825-5.716229j
    3   6.833036   4.657765+5.649944j
    4   5.150939  -0.216720-0.445046j
    5   3.174186  10.592292+0.000000j
    6   9.054791  -0.216720+0.445046j
    7   5.830278   4.657765-5.649944j
    8   5.593203  -2.977825+5.716229j
    9   4.935937   2.640720+2.231825j
    

    batching to every 15 rows

    df = pd.DataFrame({"Vibration":[random.uniform(2,10) for i in range(800)]})
    
    df.assign(
        fft=df.groupby(df.index // 15)["Vibration"].transform(lambda s: np.fft.fft(list(s)).astype("object")),
        grpfirst=df.groupby(df.index // 15)["Vibration"].transform(lambda s: list(s)[0])
    )