Convert dataframe date row to a weekend / not weekend value

Found the top voted answer in some codebase. Please don't do it that way, it's completely unreadable. Instead do:

df['weekend'] = df['date'].dt.day_name().isin(['Saturday', 'Sunday'])

Note: df['date'] needs to be in datetime64 or similar format.


One more way of getting weekend indicator is by first converting the date column to day of the week and then using those values to get weekend/not weekend. This can be implemented as follows:

df['WEEKDAY'] = pandas.to_datetime(df['DATE']).dt.dayofweek  # monday = 0, sunday = 6

df['weekend_indi'] = 0          # Initialize the column with default value of 0
df.loc[df['WEEKDAY'].isin([5, 6]), 'weekend_indi'] = 1  # 5 and 6 correspond to Sat and Sun

Here's the solution I've come up with:

df['WEEKDAY'] = ((pd.DatetimeIndex(df.index).dayofweek) // 5 == 1).astype(float)

Essentially all it does is use integer division (//) to test whether the dayofweek attribute of the DatetimeIndex is less than 5. Normally this would return just a True or False, but tacking on the astype(float) at the end returns a 1 or 0 rather than a boolean.


One more way of getting weekend indicator is by where function:

df['WEEKDAY'] = np.where((df['DATE']).dt.dayofweek) < 5,0,1)