Search code examples
pandas-groupbymeanseriesintervalsdeviation

How to split a Series into time intervals? (python)


I have this dataframe:

enter image description here

And I should split the rows of the ''Time.s'' column into intervals, calculate the average of each interval, and finally the deviation of each average.

I can't split the lines that have Volt.mv > 0.95 into a group for each second. I tried with GroupBy, but it creates problems with the second table:

enter image description here

I used this code, calculating the average directly, but I certainly did something wrong:

ecg.groupby("Time.s").apply(lambda x: x["Volt.mv"].mean())

Can anyone help me?


Solution

  • Before doing the groupby, you need to map Time.s to an interval. Otherwise each group will have only a single row (most of the time).

    Here is how to group into intervals of 0.1 seconds and compute the mean and standard deviation for each interval:

    interval_length = 0.1
    df_aggregated = (
        df
        .assign(interval=df["Time.s"].div(interval_length).astype("int").mul(interval_length))
        .groupby("interval")
        .agg(volt_mean=("Volt.mv", "mean"), volt_std=("Volt.mv", "std"))
    )