Python:根据 "Year"、"Month"、"Day" 列实现带有星期几的列?
Python: Implement a column with the day of the week based on the "Year", "Month", "Day" columns?
我尝试用星期几创建一个新列:
df2019['Weekday']=pd.to_datetime(df2019['Year'],df2019['Month'],df2019['Day']).weekday()
我收到以下错误:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
谢谢!
你可以这样做:
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)
由于您的 Timestamp
已经是 datetime
格式,您可以这样做:
df2019['weekday'] = df2019['Timestamp'].dt.weekday
我尝试用星期几创建一个新列:
df2019['Weekday']=pd.to_datetime(df2019['Year'],df2019['Month'],df2019['Day']).weekday()
我收到以下错误:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
谢谢!
你可以这样做:
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)
由于您的 Timestamp
已经是 datetime
格式,您可以这样做:
df2019['weekday'] = df2019['Timestamp'].dt.weekday