您好,我正在使用 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
你有什么想法吗? 非常感谢!
最佳答案
您的问题是 to_datetime
静默失败,因此 dtype 保持为 str/object
,如果您设置参数 errors='coerce'
那么如果任何特定字符串的转换失败,那么这些行将设置为 NaT
.
df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
因此,您需要找出这些特定行值有什么问题。
见 docs
关于python - AttributeError : Can only use . 具有 datetimelike 值的 dt 访问器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33365055/