I have a dataframe df whose index is in datetime format. I would like to make 7 new binary fields/columns indicating if the date is Monday, Tuesday, Wednesday, Thursday, Friday, Saturday or Sunday. So column Monday would have a 1 in it if it’s a Monday and a 0 otherwise, for example.
df
Is there a neat way of doing this? I have been trying but my solutions are very ugly.
Certainly! You can achieve this using the dt accessor in pandas, which allows you to access the datetime components of a Series. Here’s an example:
dt
Assuming your DataFrame df has a datetime index, you can create new binary columns for each day of the week as follows:
import pandas as pd # Assuming df has a datetime index # If not, you can convert the index to datetime using df.index = pd.to_datetime(df.index) # df.index = pd.to_datetime(df.index) # Create binary columns for each day of the week df['Monday'] = (df.index.dayofweek == 0).astype(int) df['Tuesday'] = (df.index.dayofweek == 1).astype(int) df['Wednesday'] = (df.index.dayofweek == 2).astype(int) df['Thursday'] = (df.index.dayofweek == 3).astype(int) df['Friday'] = (df.index.dayofweek == 4).astype(int) df['Saturday'] = (df.index.dayofweek == 5).astype(int) df['Sunday'] = (df.index.dayofweek == 6).astype(int)
This code uses the dayofweek property of the datetime index, which returns the day of the week where Monday is 0 and Sunday is 6. It then compares this with the day number corresponding to each day of the week, and the result is converted to binary using astype(int).
dayofweek
astype(int)
This should give you a DataFrame with new binary columns indicating the day of the week for each datetime index.