Carmen
Carmen

Reputation: 793

Add column index to existing pandas dataframe

I have a dataframe that looks as follows:

          Sim_1     Sim_2     Sim_3          
2016   1.063708  1.008885  1.028539  
2017   1.114644  0.994331  1.043218    

In order to append it to another, two-indexed dataframe, I'd like to add a new level below the existing column names, such that the dataframe will have following structure

SIMULATION  Sim_1     Sim_2     Sim_3   
IDX          LR        LR        LR
2016      1.063708  1.008885  1.028539  
2017      1.114644  0.994331  1.043218   

How would I do this?

Upvotes: 1

Views: 1246

Answers (2)

roman
roman

Reputation: 117400

You can use pandas.MultiIndex.from_product:

>>> df.columns = pd.MultiIndex.from_product([df.columns, ['LR']], names=['SIMULATION', 'IDX'])
>>> df
SIMULATION     Sim_1     Sim_2     Sim_3
IDX               LR        LR        LR
2016        1.063708  1.008885  1.028539
2017        1.114644  0.994331  1.043218

Upvotes: 1

jezrael
jezrael

Reputation: 862761

You can use MultiIndex.from_arrays:

df.columns = pd.MultiIndex.from_arrays([df.columns, 
                                       ['LR'] * len(df.columns)], 
                                       names=('SIMULATION','IDX'))
print (df)
SIMULATION     Sim_1     Sim_2     Sim_3
IDX               LR        LR        LR
2016        1.063708  1.008885  1.028539
2017        1.114644  0.994331  1.043218

Upvotes: 1

Related Questions