Home > front end >  Convert datetime to 0 or 1 depending on if it´s weekend or not
Convert datetime to 0 or 1 depending on if it´s weekend or not

Time:09-17

I have a dataframe with Date and Expenses by citizen.

I want to create a new column that has 1 or 0 values depending on whether the date is weekend or not.

What I thought of doing was, first of all creating an empty column called weekend.

Activity['Weekend'] = Activity.apply(lambda _: '', axis=1)

Then, converting date to days of the week, and create values 0 or 1 for each row of Weekend column depending on Date value.

Something like:

dataset3['Date'] = pd.to_datetime(dataset3['Date'])
dataset3['Date'] = dataset3.Date.dt.dayofweek 

dataset3.Weekend[(dataset3.Day == '0') | (dataset3.Day == '1') | (dataset3.Day == '2') | (dataset3.Day == '3') | (dataset3.Day == '4')] = 0
dataset3.Weekend[(dataset3.Day == '5') | (dataset3.Day == '6')] = 1

However, the las two lines of code are not working properly. Any idea?

CodePudding user response:

Try this one-liner instead:

dataset3['Date'] = dataset3.Date.dt.dayofweek.gt(4).astype(int)
  • Related