问题描述:

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?

网友答案:

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
相关阅读:
Top