简体   繁体   中英

Convert MultiIndex Names to DataFrame Column Values & Rename DataFrame Columns

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM