【发布时间】:2015-10-27 10:10:38
【问题描述】:
您好,我正在使用 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("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
你有什么想法吗? 非常感谢!
【问题讨论】: