Mario L
Mario L

Reputation: 577

Pandas timeseries replace weekend with one value generated from the weekend mean

I have a multicolumn pandas dataframe, with rows for each day. Now I would like to replace each weekend with it's mean values in one row.

I.e. (Fr,Sa,Su).resample().mean() --> (Weekend)

Not sure where to start even.

Thank you in advance.

Upvotes: 1

Views: 139

Answers (1)

Andrew Lavers
Andrew Lavers

Reputation: 4378

import pandas as pd
from datetime import timedelta
# make some data
df = pd.DataFrame({'dt': pd.date_range("2018-11-27", "2018-12-12"), "val": range(0,16)})

# adjust the weekend dates to fall on the friday
df['shifted'] = [d - timedelta(days = max(d.weekday() - 4, 0)) for d in df['dt']]

# calc the mean
df2 =  df.groupby(df['shifted']).val.mean()
df2

#Out[105]: 
#shifted
#2018-11-27     0
#2018-11-28     1
#2018-11-29     2
#2018-11-30     4
#2018-12-03     6
#2018-12-04     7
#2018-12-05     8
#2018-12-06     9
#2018-12-07    11
#2018-12-10    13
#2018-12-11    14
#2018-12-12    15

Upvotes: 1

Related Questions