1

I have below Dataframe with MultiIndex columns, need to prepare regular dataframe

df:

Instrument PDKRW1M
Field           ER
Date              
2019-02-28  1124.0
2019-03-01  1125.5
2019-03-04  1126.0
2019-03-05  1126.5
2019-03-06  1127.0
2019-03-07  1132.0
2019-03-08  1133.5
2019-03-11  1133.0
2019-03-12  1128.0
2019-03-13  1129.5
2019-03-14  1135.0

df.columns:

MultiIndex(levels=[['PDKRW1M'], ['ER']],
       labels=[[0], [0]],
       names=['Instrument', 'Field'])

Want to prepare dataframe like this:

Date    Value   Instrument  Field
2019-02-28  1124.0  PDKRW1M ER
2019-03-01  1125.5  PDKRW1M ER
2019-03-04  1126.0  PDKRW1M ER
2019-03-05  1126.5  PDKRW1M ER
2019-03-06  1127.0  PDKRW1M ER
2019-03-07  1132.0  PDKRW1M ER
2019-03-08  1133.5  PDKRW1M ER
2019-03-11  1133.0  PDKRW1M ER
2019-03-12  1128.0  PDKRW1M ER
2019-03-13  1129.5  PDKRW1M ER
2019-03-14  1135.0  PDKRW1M ER
2019-03-14  1135.0  PDKRW1M ER

1 Answer 1

2

Use DataFrame.unstack with DataFrame.reset_index with first and second level for DatetimeIndex:

df = df.unstack().reset_index(level=[0,1], name='Value')
#for column Date
#df = df.unstack().reset_index(name='Value')
print (df)
           Instrument Field   Value
Date                               
2019-02-28    PDKRW1M    ER  1124.0
2019-03-01    PDKRW1M    ER  1125.5
2019-03-04    PDKRW1M    ER  1126.0
2019-03-05    PDKRW1M    ER  1126.5
2019-03-06    PDKRW1M    ER  1127.0
2019-03-07    PDKRW1M    ER  1132.0
2019-03-08    PDKRW1M    ER  1133.5
2019-03-11    PDKRW1M    ER  1133.0
2019-03-12    PDKRW1M    ER  1128.0
2019-03-13    PDKRW1M    ER  1129.5
2019-03-14    PDKRW1M    ER  1135.0

If necessary change order of columns:

df = df[df.columns[-1:].tolist() + df.columns[:-1].tolist()]
#for column Date
#df = df[df.columns[-2:].tolist() + df.columns[:-2].tolist()]
print (df)
             Value Instrument Field
Date                               
2019-02-28  1124.0    PDKRW1M    ER
2019-03-01  1125.5    PDKRW1M    ER
2019-03-04  1126.0    PDKRW1M    ER
2019-03-05  1126.5    PDKRW1M    ER
2019-03-06  1127.0    PDKRW1M    ER
2019-03-07  1132.0    PDKRW1M    ER
2019-03-08  1133.5    PDKRW1M    ER
2019-03-11  1133.0    PDKRW1M    ER
2019-03-12  1128.0    PDKRW1M    ER
2019-03-13  1129.5    PDKRW1M    ER
2019-03-14  1135.0    PDKRW1M    ER
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.