Reputation: 141
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.
Upvotes: 1
Views: 719
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 year
s:
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