AttributeError: 只能在 datetimelike 值上使用 .dt 访问器

12 浏览
0 Comments

AttributeError: 只能在 datetimelike 值上使用 .dt 访问器

你好,我正在使用pandas将一列转换为月份。当我读取数据时,它们是对象类型:

Date           object
dtype: object

所以我先将它们转换为日期时间,然后尝试将它们转换为月份:

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')

所以,我得到的错误信息如下:

/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("只能在日期时间类型的值上使用.dt访问器")
   2529 
   2530 
AttributeError: 只能在日期时间类型的值上使用.dt访问器

编辑后:

日期列的样式如下:

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 

你有任何想法吗?

非常感谢!

0