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

2
  • Nope, not working. Gets a really long exception, I'll post it in the question. Commented Feb 10, 2020 at 3: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 Commented Feb 10, 2020 at 3:40

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

hello ryan! please mark the question as closed by checking the green tick.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.