【问题标题】:Python: Implement a column with the day of the week based on the "Year", "Month", "Day" columns?Python:根据“年”、“月”、“日”列实现带有星期几的列?
【发布时间】:2020-10-17 23:25:21
【问题描述】:

我尝试用星期几创建一个新列:

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().

谢谢!

【问题讨论】:

    标签: python pandas dataframe date weekday


    【解决方案1】:

    你可以这样做:

    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)
    

    【讨论】:

    • 很高兴我能帮上忙 :)
    【解决方案2】:

    由于您的Timestamp 已经是datetime 格式,您可以这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 2020-01-16
      • 1970-01-01
      • 2014-09-17
      • 1970-01-01
      相关资源
      最近更新 更多