Miles Bennet Dyson
Miles Bennet Dyson

Reputation: 141

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.

enter image description here

Upvotes: 1

Views: 719

Answers (1)

jezrael
jezrael

Reputation: 862601

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

Upvotes: 1

Related Questions