-
-
Save Mahyar24/9ecad1892691983045e65c0f015a3d88 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import pandas as pd | |
def pretty_time(sec: int) -> str: | |
return time.strftime("%H:%M:%S", time.gmtime(sec)) | |
def generate_time_intervals( | |
series: pd.Series, rolling_window: int = 5, threshold: int = 2 | |
) -> list[tuple[str, str]]: | |
assert rolling_window >= threshold, "rolling_window must be greater than threshold" | |
return ( | |
series.rolling(rolling_window) | |
.sum()[lambda x: x >= threshold] | |
.index.to_series() | |
.pipe( | |
lambda ser_: ser_.groupby(ser_.diff().ne(1).cumsum()).agg(["first", "last"]) | |
) | |
.agg(["first", "last"]) | |
.loc[lambda df_: (df_["last"] - df_["first"]) >= rolling_window] | |
.apply( | |
{ | |
"first": lambda x: max(0, x - rolling_window + threshold), | |
"last": lambda x: max(0, x - rolling_window), | |
} | |
) | |
.applymap(pretty_time) | |
.apply(tuple, 1) | |
.tolist() | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment