Miguel Gonzalez
Miguel Gonzalez

Reputation: 446

Python: Implement a column with the day of the week based on the "Year", "Month", "Day" columns?

enter image description here

enter image description here

I try to create a new column with the day of the week:

df2019['Weekday']=pd.to_datetime(df2019['Year'],df2019['Month'],df2019['Day']).weekday()

And I get the following error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Thanks!

Upvotes: 1

Views: 296

Answers (2)

Partha Mandal
Partha Mandal

Reputation: 1441

Since your Timestamp is already of datetime format, you can do this:

df2019['weekday'] = df2019['Timestamp'].dt.weekday

Upvotes: 2

Anwarvic
Anwarvic

Reputation: 12992

You can do something like this:

from datetime import datetime

def get_weekday(row):
    date_str = "{}-{}-{}".format(row["Year"], row["Month"], row["Day"])
    date = datetime.strptime(date_str, '%Y-%m-%d')
    return date.weekday()


df2019["weekday"] = df2019.apply(get_weekday, axis=1)

Upvotes: 3

Related Questions