【问题标题】:"AttributeError: Can only use .dt accessor with datetimelike values" when trying to extract year from a date column [duplicate]尝试从日期列中提取年份时,“AttributeError: Can only use .dt accessor with datetimelike values”
【发布时间】:2018-02-26 12:30:01
【问题描述】:

我得到一个日期框,其中有一列“brth_dt”,它的类型是 datetime64[ns]。我想提取人的年龄,但是当输入时: all_df['brth_dt'].dt.year 或
all_df['age'] = (pd.datetime.today().year - all_df['brth_dt'].dt.year)

出现错误:只能使用具有类似日期时间值的 .dt 访问器

brth_dt 列是这样的:

    brth_date
1   14Oct1978
2   21Aug1970
3   06Jan1980
4   09Mar1992

有什么建议吗?谢谢!

【问题讨论】:

    标签: python pandas datetime dataframe


    【解决方案1】:

    您需要先使用将列转换为日期时间

    df['brth_date'] = pd.to_datetime(df['brth_date'], format = '%d%b%Y')
    

    你可以使用 dt 访问器

    df['brth_date'].dt.year
    

    你得到

    1    1978
    2    1970
    3    1980
    4    1992
    

    【讨论】:

    • thanks..hiwever,df.info() 显示此列是 datetime64[ns] 和 df['brth_date'] = pd.to_datetime(df['brth_date'], format = '%d %b%Y') 出现 KeyError
    • 这令人惊讶,因为日期时间值通常采用 1978-10-14 格式。确切的 keyerror 消息是什么?
    • 是的,它的类型是 datetime64[ns] 和 14Oct1978 格式,这就是我很好奇...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多