Joris Kinable
Joris Kinable

Reputation: 2411

Inserting column into dataframe with multi-level index

I've created a dataframe data which is a concatenation of various columns as follows:

import pandas as pd
data_lp = pd.read_csv("fil1.csv",sep=",", comment='#')
data_mip = pd.read_csv("file2.csv",sep=",", comment='#')
data=pd.concat([data_lp[['name','vars','con']],
                data_lp[['obj','t(ms)']],
                data_mip[['obj','t(ms)']]],
               keys=['','LP', 'MIP'],
               sort=False,axis=1)

Result:

                         LP                 MIP
    name    vars    con  obj        t(ms)   obj t(ms)
0   bop0    50      6    573.531624 155     285.0   252
1   bop1    50      6    420.036781 223     247.0   334

Now I would like to insert a new column gap under MIP, in between the columns obj and t(ms). How can I do this?

gap=(data['LP']['obj']-data['MIP']['obj'])/data['MIP']['obj']
data['MIP'].insert(1,'gap',gap) #this doesn't work

Upvotes: 1

Views: 28

Answers (1)

jezrael
jezrael

Reputation: 862471

Use tuple for assign value in MultiIndex, also is necessary change 1 to 6 for new sixth column:

data.insert(6,('MIP','gap'),gap)
print (data)
                          LP          MIP                
   name vars con         obj t(ms)    obj       gap t(ms)
0  bop0   50   6  573.531624   155  285.0  1.012392   252
1  bop1   50   6  420.036781   223  247.0  0.700554   334

Upvotes: 1

Related Questions