spcol
spcol

Reputation: 433

Convert MultiIndex to single date

I have a dataframe whereby the index is a multiindex as follows;

     1
     2
     3
     4
     5
2020 6
     7
     8
     9
     10
     11
     12

As I need daily values I'm looking to convert it to a columns which would be as follows;

Date
2020/01/01
2020/02/01
2020/03/01
2020/04/01
2020/05/01

etc 

so that I can then use;


df.set_index('Date').resample('D').ffill()

Any help much appreciated!

Upvotes: 1

Views: 56

Answers (1)

jezrael
jezrael

Reputation: 862641

If in index are only year and month levels use list comprehension with change format for joined strings:

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

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

If ther are also days:

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

#python 2
df.index = pd.to_datetime(['{}-{}-{}'.format(a, b, c) for a, b, c in df.index])

And then:

df1 = df.resample('D').ffill()

Upvotes: 2

Related Questions