How to round dates to week starts in Pandas
import pandas as pd
df['Date'] - pd.to_timedelta(df['Date'].dt.dayofweek, unit='d')
Here is an alternative approach for calculating beginning of the week series by using convenience method pd.DateOffset(weekday=0,weeks=1)
:
import pandas as pd, numpy as np
df=pd.DataFrame({'date':pd.date_range('2016-10-01','2016-10-31')})
df['BeginWeek']=np.where(df.date.dt.weekday==0, # offset on Non Mondays only
df['date'],
df['date']-np.timedelta64(1,'W')),
)
Thanks to ribitskyib np.where
was added to pick current Monday when date is already Monday. Confirmation that the above works now:
Some additional ideas provided by others:
Here is a quick list of days of the week:
df['BeginWeek'].dt.strftime("%a").unique()
array(['Mon'], dtype=object)
and the days in the original column are:
df['date'].dt.strftime("%a").unique()
array(['Sat', 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri'], dtype=object)