Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

python - AttributeError: Can only use .dt accessor with datetimelike values

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

Also if that helps:

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

EDITED:

Date columns are like this:

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!

question from:https://stackoverflow.com/questions/33365055/attributeerror-can-only-use-dt-accessor-with-datetimelike-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

See the docs


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...