Home > OS >  DataFrame to multilevel columns dataframe
DataFrame to multilevel columns dataframe

Time:10-19

Having this initial dataframe :

print (df)
         Tenor  IV  RV
Ccy Pair              
EURUSD      1M   5   6
EURUSD      3M   5   6
EURUSD      6M   5   6
EURUSD      1Y   5   6
USDJPY      1M   5   6
USDJPY      3M   5   6
USDJPY      6M   5   6
USDJPY      1Y   5   6
GBPUSD      1M   5   6
GBPUSD      3M   5   6
GBPUSD      6M   5   6
GBPUSD      1Y   5   6

I would like to convert it to multi column one, such that the result is something like

          1M        3M        6M         1Y
CcyPair  RV | IV    RV | IV   RV | IV    RV | IV
 ----------------------------------------------
 EURUSD   5   6     5    6    5     6     5   6
 USDJPY   5   6     5    6    5     6     5   6
   ......

Is there a nice way to achieve this without creating manually single arrays from the original dataframe and convert it using multiIndex ?

CodePudding user response:

Use DataFrame.stack with Series.unstack:

df = df.set_index('Tenor', append=True).stack().unstack([1,2])
print (df)
Tenor    1M    3M    6M    1Y   
         IV RV IV RV IV RV IV RV
Ccy Pair                        
EURUSD    5  6  5  6  5  6  5  6
GBPUSD    5  6  5  6  5  6  5  6
USDJPY    5  6  5  6  5  6  5  6
  • Related