Home > Back-end >  How do I convert the month and day in dataset to datetime so that I can index it?
How do I convert the month and day in dataset to datetime so that I can index it?

Time:01-06

End goal: I want to create a graph so that the x-axis is the date and there are two y-axis, one Ontario and one CMB. Ultimately there would be 5 graphs (Ontario,2 vs CMB,2 & Ontario,3 vs CMB,3 & etc.)

Ideal Graph

However, my datasets have date as "mm-dd" in the Datestamp column which are object type. Also, both tables do not have all the same dates.

dfplot_ont.tail()

    Datestamp   Ontario,2   Ontario,3   Ontario,4   Ontario,5   Ontario,7
18  12-29   -0.664715   0.245738    0.668187    0.016819    -0.493384
19  12-30   0.491311    0.302230    1.140404    1.421685    1.552911
20  01-02   1.213827    0.471704    1.400124    1.599767    1.621120
21  01-03   1.502834    0.048018    0.927907    0.956694    1.052705
22  01-04   -1.965244   -2.917788   0.597355    0.234474    -0.857170


dfplot_cmb.tail()

    Datestamp   CMB,2           CMB,3           CMB,4           CMB,5           CMB,7
15  12-28   0.907092    0.937362    0.991568    1.030808    1.139708
16  12-29   0.900410    0.919994    0.992267    0.991359    1.034978
17  12-30   1.181259    1.193806    1.272700    1.283576    1.265860
18  01-03   0.751646    0.752037    0.681900    0.686982    0.600167
19  01-04   0.606714    0.532544    0.339825    0.282894    0.127186

I need to change this to datetime but it seems like I need to include a year to change it. How do I code "if the month is 12, then year is 2022 and if the month is 1, then year is 2023"? I will also need to swap it out for the year will always be 2023 once there is data at the end of the year.

I have tried this, but it does not change Datestamp to datetime type:

dfplot_ont['Datestamp'] = pd.to_datetime(dfplot_ont['Datestamp'], format='%m-%d').dt.strftime('%m-%d')

I have also tried this, but then the index ends up not being mm-dd:

dfplot_ont = dfplot_ont.set_index(pd.to_datetime(dfplot_ont['Datestamp'], format='%MM-           
  • Related