Reputation: 413
I have a Dataframe, df, with 3 columns: Year, Month and Date. I want to use this information to determine if this date falls on a weekend or weekday and which day of the week it is.
I am trying to use the below code to determine if its weekend or weekday but it is not working
from datetime import datetime
from datetime import date
def is_weekend(d = datetime.today()):
return d.weekday() > 4
df['weekend'] = df.apply(lambda x: is_weekend(date(x['Year'], x['Month'], x['Day'])), axis=1)
I am getting this error:
TypeError: cannot convert the series to <class 'int'>
Apart from this, how do I find out if this date falls on which day of the week.
Upvotes: 11
Views: 23023
Reputation: 3305
How about we do it in a readable self-explanatory way?
dates = pd.to_datetime({"year": df.Year, "month": df.Month, "day": df.Day})
df["Is Weekend"] = dates.dt.day_name().isin(['Saturday', 'Sunday'])
Upvotes: 7
Reputation: 18306
You can first form a dates
series from your Year
, Month
and Day
columns:
dates = pd.to_datetime({"year": df.Year, "month": df.Month, "day": df.Day})
then you can check the dayofweek
(note the dt
accessor before it):
df["Day of Week"] = dates.dt.dayofweek
and form the is_weekend
column with your logic:
df["Is Weekend"] = dates.dt.dayofweek > 4
where we don't need apply
anymore since we have a unified dates
series and it supports this kind of all-at-once comparison.
Upvotes: 25