Skip to content

Instantly share code, notes, and snippets.

@Mahyar24
Created June 10, 2022 17:52
Show Gist options
  • Save Mahyar24/29fb49f9c8043b4fbc0f44e5cf93d276 to your computer and use it in GitHub Desktop.
Save Mahyar24/29fb49f9c8043b4fbc0f44e5cf93d276 to your computer and use it in GitHub Desktop.
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