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

Time:04-26

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.

enter image description here

CodePudding user response:

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')
  • Related