Hi I am using pandas to convert a column to month. When I read my data they are objects:
JavaScript
x
3
1
Date object
2
dtype: object
3
So I am first making them to date time and then try to make them as months:
JavaScript
1
6
1
import pandas as pd
2
file = '/pathtocsv.csv'
3
df = pd.read_csv(file, sep = ',', encoding='utf-8-sig', usecols= ['Date', 'ids'])
4
df['Date'] = pd.to_datetime(df['Date'])
5
df['Month'] = df['Date'].dt.month
6
Also if that helps:
JavaScript
1
3
1
In [10]: df['Date'].dtype
2
Out[10]: dtype('O')
3
So, the error I get is like this:
JavaScript
1
9
1
/Library/Frameworks/Python.framework/Versions/2.7/bin/User/lib/python2.7/site-packages/pandas/core/series.pyc in _make_dt_accessor(self)
2
2526 return maybe_to_datetimelike(self)
3
2527 except Exception:
4
-> 2528 raise AttributeError("Can only use .dt accessor with datetimelike "
5
2529 "values")
6
2530
7
8
AttributeError: Can only use .dt accessor with datetimelike values
9
EDITED:
Date columns are like this:
JavaScript
1
11
11
1
0 2014-01-01
2
1 2014-01-01
3
2 2014-01-01
4
3 2014-01-01
5
4 2014-01-03
6
5 2014-01-03
7
6 2014-01-03
8
7 2014-01-07
9
8 2014-01-08
10
9 2014-01-09
11
Do you have any ideas? Thank you very much!
Advertisement
Answer
Your problem here is that to_datetime
silently failed so the dtype remained as str/object
, if you set param errors='coerce'
then if the conversion fails for any particular string then those rows are set to NaT
.
JavaScript
1
2
1
df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
2
So you need to find out what is wrong with those specific row values.
See the docs