您好,我正在使用 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
你有什么想法?非常感谢你!
原文由 Nasia Ntalla 发布,翻译遵循 CC BY-SA 4.0 许可协议
你的问题是
to_datetime
默默地失败了,所以 dtype 仍然是str/object
,如果你设置参数errors='coerce'
的话,那么如果任何特定的行转换失败那么字符串转换—设置为NaT
。因此,您需要找出那些特定行值有什么问题。
查看 文档