0

I'm working with a pandas dataframe in which one column is a datetime64 object. I need to plot a bar chart of the number of rows per year, and also slice the dataframe for a month range (e.g. January 2011 to March 2011). I suppose I could add a column that captures only the year or month, but how can I do so?

I ran

df['year'], df['month'] = df['date'].dt.year, df['date'].dt.month
df

but got an AttributeError: Can only use .dt accessor with datetimelike values

Ryan Chng
  • 117
  • 4
  • 10
  • Nope, not working. Gets a really long exception, I'll post it in the question. – Ryan Chng Feb 10 '20 at 03:18
  • Hmm ok. I reran some more code from my notebook and it seems to be working well - so I would guess that it's because when I got the exception, I hadn't re-ran the conversion of to_datetime – Ryan Chng Feb 10 '20 at 03:40

1 Answers1

0

What worked was, as answered in other questions:

df['date'] = pd.to_datetime(df['date'])
df['year'], df['month'] = df['date'].dt.year, df['date'].dt.month

What made my situation different was that I did my work on a Jupyter notebook last night and went to sleep. So when I booted my computer again, the lines of code that included the conversion of my datetime column to a datetime64 object had not been run. Silly me. After I reran them, the code worked.

Ryan Chng
  • 117
  • 4
  • 10