我正在使用pandas版本0.16.2。我想提取日期列的年份和月份。
我读了数据
df = pd.read_csv(raw_data.csv,
parse_dates=['EOM_DEFAULT_DATE','RESOLUTION_DATE'], low_memory=False)
'EOM_DEFAULT_DATE'看起来像:
0 31-JAN-07 12.00.00.000000000 AM
1 31-JAN-07 12.00.00.000000000 AM
Name: EOM_DEFAULT_DATE, dtype: object
'RESOLUTION DATE'看起来像:
0 2008-03-31
1 2008-03-31
Name: RESOLUTION_DATE, dtype: datetime64[ns]
具体来说,我想以这种方式提取Year,但是得到这个错误:
df['YEAR']=pd.DatetimeIndex(df['RESOLUTION_DATE']).year
---
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
另外,我在尝试提取月份时遇到错误:
df['MNTH']=pd.DatetimeIndex(df['EOM_DEFAULT_DATE']).month
---
File "<ipython-input-61-d7aec9a17a8f>", line 1, in <module>
File "C:\Continuum\Anaconda\lib\site-packages\pandas\util\decorators.py", line 88, in wrapper
return func(*args, **kwargs)
File "C:\Continuum\Anaconda\lib\site-packages\pandas\tseries\index.py", line 292, in __new__
yearfirst=yearfirst)
File "C:\Continuum\Anaconda\lib\site-packages\pandas\tseries\index.py", line 1936, in _str_to_dt_array
data = _algos.arrmap_object(arr, parser)
File "pandas\src\generated.pyx", line 2295, in pandas.algos.arrmap_object (pandas\algos.c:77984)
File "C:\Continuum\Anaconda\lib\site-packages\pandas\tseries\index.py", line 1932, in parser
yearfirst=yearfirst)
File "C:\Continuum\Anaconda\lib\site-packages\pandas\tseries\tools.py", line 494, in parse_time_string
raise DateParseError(e)
DateParseError: unknown string format
使用这个确切的代码,我知道其他人可以正常运行代码,并提取年份和月份。我错过了什么?
答案 0 :(得分:2)
您可以使用.dt
访问者在价值为pd.Series
的{{1}}上获取年份和月份。
datetime64
要解析日期,您需要提供日期时间格式。
df['YEAR'] = df['RESOLUTION_DATE'].dt.year
也许在阅读csv时尝试不解析日期,因为你有两个日期列并且它们有不同的格式。只需读入原始字符串即可。然后在pandas中将字符串转换为datetime对象。
dt_str = '31-JAN-07 12.00.00.000000000 AM'
fmt = '%d-%b-%y %H.%M.%S.%f %p'
pd.to_datetime(dt_str, format=fmt)
#output: Timestamp('2007-01-31 12:00:00')