How to apply to_datetime on pandas Dataframe column?

I have a dataframe with Timestamp entries in one column, created from strings like so:

df = pd.DataFrame({"x": pd.to_datetime("MARCH2016")})

Now I want to select from df based on month, cutting across years, by accessing the .month attribute of the datetime object. However, to_datetime actually created a Timestamp object from the string, and I can't seem to coerce it to datetime. The following works as expected:

type(df.x[0].to_datetime())  # gives datetime object

but using apply (which in my real life example of course I want to do given that I have more than one row) doesn't:

type(df.x.apply(pd.to_datetime)[0]) # returns Timestamp

What am I missing?

Answers


The fact that it's a TimeStamp is irrelevant here, you can still access the month attribute using .dt accessor:

In [79]:
df = pd.DataFrame({"x": [pd.to_datetime("MARCH2016")]})
df['x'].dt.month

Out[79]:
0    3
Name: x, dtype: int64

Need Your Help

PHP Registration Form not processing AJAX data

javascript php jquery ajax forms

I may be being stupid, but I am trying to process a registration form using an AJAX call to a PHP page. My PHP page is working perfectly on it's own, but when I try to post the form data to the PHP...

Zend OAuth with twitter single access tokens

php api zend-framework twitter oauth

I'm developing an application where it requires users to sign in using twitter and OAuth. Everything works just fine thanks to Zend_OAuth. The problem is that the web app will also make some calls ...