Skip to content

Commit

Permalink
my.body.sleep: massive speedup for average temperature calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
karlicoss committed Nov 11, 2023
1 parent 37643c0 commit bde43d6
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions my/body/sleep/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,21 @@ def dataframe(self, with_temperature: bool=True) -> DataFrameT:
bdf = BM.dataframe()
temp = bdf['temp']

# sort index and drop nans, otherwise indexing with [start: end] gonna complain
temp = pd.Series(
temp.values,
index=pd.to_datetime(temp.index, utc=True)
).sort_index()
temp = temp.loc[temp.index.dropna()]

def calc_avg_temperature(row):
start = row['sleep_start']
end = row['sleep_end']
if pd.isna(start) or pd.isna(end):
return None

between = (start <= temp.index) & (temp.index <= end)
# on no temp data, returns nan, ok
return temp[between].mean()
return temp[start: end].mean()

df['avg_temp'] = df.apply(calc_avg_temperature, axis=1)
return df
Expand Down

0 comments on commit bde43d6

Please sign in to comment.