Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to plot a time series with multi-index of month and year

I try to plot a time series where the multi-index is equal to the year and month. This makes python crash when I try to plot with matplotlib. How can I combine these two indexes into one index that is just a date_time variable?

So what I want is to combine the multi-index into one index, changing the two columns into one column (e.g.: 2018 1 –> 2018/01). How can I achieve this?

The picture below shows the dataframe I’m working with.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

>Solution :

Use list comprehension:

df.index = pd.to_datetime([f'{a}-{b}-01' for a, b in df.index])

If possible converting to integers years:

df.index = pd.to_datetime([f'{int(a)}-{b}-01' for a, b in df.index])

If possible converting to integers failed, because missing values use:

df.index = pd.to_datetime([f'{a}-{b}-01' for a, b in df.index], errors='coerce')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading