【问题标题】:Error message trying to change string to year尝试将字符串更改为年份的错误消息
【发布时间】:2020-09-21 02:14:34
【问题描述】:

我正在尝试组合三个字段来创建日期,年份当前是字符串: 将字符串更改为日期时间的代码:

f2[:,'frt_eli_year'] = pd.to_datetime(f2['frt_eli_year'].astype(str), format='%Y',errors='coerce',utc=True)

错误信息:

TypeError: unhashable type: 'slice'

然后编码加入年月日:

f2[:,'test'] = pd.to_datetime(f2['frt_eli_year'].dt.year,f2['frt_eli_year'].dt.month,f2['frt_eli_year'].dt.day)

感谢您的帮助,谢谢!

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    错误在f2[:,'frt_eli_year']。检查此this answer。基本上,如果您更改为f2.loc[:,'frt_eli_year'],或者因为您想要所有行,则只需f2['frt_eli_year']

    总共:

    f2['frt_eli_year'] = pd.to_datetime(f2['frt_eli_year'], 
                                        format='%Y', errors='coerce', utc=True)
    

    【讨论】:

    • 谢谢你错过了代码中没有的 loc:现在尝试合并 3 个字段并得到:
    • AttributeError: Can only use .dt accessor with datetimelike values
    • f2.loc[:'test'] = pd.to_datetime(f2['first_elig_year'].dt.year,f2['pol_eff_date_mth'].dt.month,f2['pol_eff_date_day'] .dt.day)
    • f2.loc[:,'pol_eff_date_mth'] = f2['pol_eff_date'].dt.month f2.loc[:,'pol_eff_date_day'] = f2['pol_eff_date'].dt.day
    • 既然这是另一个问题,你应该在一个新问题中问它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多