Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you extract both year AND month from date in Pandas

I have a dataframe with a date column (type datetime). I can easily extract the year or the month to perform groupings, but I can't find a way to extract both year and month at the same time from a date. I need to analyze performance of a product over a 1 year period and make a graph with how it performed each month. Naturally I can't just group by month because it will add the same months for 2 different years, and grouping by year doesn't produce my desired results because I need to look at performance monthly.

I've been looking at several solutions, but none of them have worked so far.

So basically, my current dates look like this

2018-07-20
2018-08-20
2018-08-21
2018-10-11
2019-07-20
2019-08-21

And I'd just like to have 2018-07, 2018-08, 2018-10, and so on.

like image 913
Dasphillipbrau Avatar asked Dec 06 '22 09:12

Dasphillipbrau


1 Answers

You can use to_period

df['month_year'] = df['date'].dt.to_period('M')
like image 186
ATL Avatar answered Dec 10 '22 09:12

ATL