I have a big DataFrame
with millions of rows and one of the columns as date
. I want to add 5 columns to it which are 0/1 for weekdays.
dates = pd.date_range('1700-01-01', '2017-07-02')
df = pd.DataFrame({'date':dates, 'Values':np.random.normal(size = len(dates))})
df
date value
0 1700-01-01 -1.239422
1 1700-01-02 -0.209840
2 1700-01-03 0.146293
3 1700-01-04 1.422454
4 1700-01-05 0.453222
...
I am trying to achieve this as follows:
df['isMonday'] = df.apply(lambda x: 1 if x['date'].weekday() == 0 else 0, axis=1)
df['isTuesday'] = df.apply(lambda x: 1 if x['date'].weekday() == 1 else 0, axis=1)
df['isWednesday'] = df.apply(lambda x: 1 if x['date'].weekday() == 2 else 0, axis=1)
df['isThursday'] = df.apply(lambda x: 1 if x['date'].weekday() == 3 else 0, axis=1)
df['isFriday'] = df.apply(lambda x: 1 if x['date'].weekday() == 4 else 0, axis=1)
df
date value isMonday isTuesday isWednesday isThursday isFriday
0 1700-01-01 -1.239422 0 0 0 0 1
1 1700-01-02 -0.209840 0 0 0 0 0
2 1700-01-03 0.146293 0 0 0 0 0
3 1700-01-04 1.422454 1 0 0 0 0
4 1700-01-05 0.453222 0 1 0 0 0
...
This is very slow. What would be the most efficient way to achieve this.