【问题标题】:"AttributeError: Can only use .dt accessor with datetimelike values" while trying to fetch day of the week“AttributeError: Can only use .dt accessor with datetimelike values”同时尝试获取星期几
【发布时间】:2020-04-16 14:17:23
【问题描述】:

我在尝试获取一周中的特定日期时收到以下错误。我使用的代码如下:

df['weekday'] = df['Date'].dt.dayofweek

日期格式如下。

但是,我无法获取一周中的以下几天,并且收到如下错误:

AttributeError: Can only use .dt accessor with datetimelike values

有人可以帮我解决这个问题吗?

【问题讨论】:

标签: python-3.x pandas dataframe python-datetime


【解决方案1】:

错误表明 .dt 访问器只能与 'datetimelike' 值一起使用。不幸的是,您的问题不完整,因为您没有向我们展示“日期”列的 dtype,请参阅How to create a Minimal, Reproducible Example。但如果 dtype 不是 'datetime64[ns]' 我从你的画中得出它必须是 'object' (字符串)。

解决方案:将对象转换为日期时间,然后使用 .dt 访问器:

df['weekday'] = df['Date'].apply(pd.to_datetime).dt.dayofweek

您示例中的结果全为零,因为 2005-07-25 是星期一。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多