AttributeError:只能将.dt访问器与类似datetime的值一起使用 [英] AttributeError: Can only use .dt accessor with datetimelike values

查看:102
本文介绍了AttributeError:只能将.dt访问器与类似datetime的值一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用pandas将列转换为月份. 当我读取数据时,它们就是对象:

Hi I am using pandas to convert a column to month. When I read my data they are objects:

Date           object
dtype: object

因此,我首先将它们设置为日期时间,然后尝试将其设置为几个月:

So I am first making them to date time and then try to make them as months:

import pandas as pd
file = '/pathtocsv.csv'
df = pd.read_csv(file, sep = ',', encoding='utf-8-sig', usecols= ['Date', 'ids'])    
df['Date'] = pd.to_datetime(df['Date'])
df['Month'] = df['Date'].dt.month

如果有帮助,也可以:

In [10]: df['Date'].dtype
Out[10]: dtype('O')

所以,我得到的错误是这样的:

So, the error I get is like this:

/Library/Frameworks/Python.framework/Versions/2.7/bin/User/lib/python2.7/site-packages/pandas/core/series.pyc in _make_dt_accessor(self)
   2526             return maybe_to_datetimelike(self)
   2527         except Exception:
-> 2528             raise AttributeError("Can only use .dt accessor with datetimelike "
   2529                                  "values")
   2530 

AttributeError: Can only use .dt accessor with datetimelike values

日期列如下:

0         2014-01-01         
1         2014-01-01         
2         2014-01-01         
3         2014-01-01         
4         2014-01-03       
5         2014-01-03         
6         2014-01-03         
7         2014-01-07         
8         2014-01-08         
9         2014-01-09 

您有什么想法吗? 非常感谢你!

Do you have any ideas? Thank you very much!

推荐答案

您的问题是to_datetime静默失败,因此dtype仍为str/object,如果您将参数errors='coerce'设置为任何值,则转换失败特定的字符串,然后将这些行设置为NaT.

Your problem here is that to_datetime silently failed so the dtype remained as str/object, if you set param errors='coerce' then if the conversion fails for any particular string then those rows are set to NaT.

df['Date'] = pd.to_datetime(df['Date'], errors='coerce')

因此,您需要找出那些特定的行值出了什么问题.

So you need to find out what is wrong with those specific row values.

请参见文档

这篇关于AttributeError:只能将.dt访问器与类似datetime的值一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆