pandas dataframe,AttributeError: Can only use .dt accessor with datetimelike values

  • pandas dataframe 中将类似2019-01-12的日期格式列转化为20190112的日期格式时,报错如下:
File "C:\Users\seagull\AppData\Roaming\Python\Python36\site-packages\pandas\core\indexes\accessors.py", line 325, in __new__
    raise AttributeError("Can only use .dt accessor with datetimelike "
AttributeError: Can only use .dt accessor with datetimelike values
  • 原始代码

predict_dataset = dataset3[['User_id', 'Coupon_id', 'Date_received']].copy()
        predict_dataset.Date_received = predict_dataset.Date_received.dt.strftime('%Y%m%d')
  • 解决代码:

  • 增加第二行,首先将字符串列转化为日期列;然后再进行日期格式间的转换就可以了。
predict_dataset = dataset3[['User_id', 'Coupon_id', 'Date_received']].copy()
        predict_dataset.Date_received = pd.to_datetime(predict_dataset.Date_received, format='%Y-%m-%d')
        predict_dataset.Date_received = predict_dataset.Date_received.dt.strftime('%Y%m%d')

你可能感兴趣的:(Machine,Learning,python,pandas,日期)