简体   繁体   中英

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

在此处输入图像描述

在此处输入图像描述

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!

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)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM