使用多级索引将列插入数据框

时间:2019-07-07 15:17:52

标签: python-3.x pandas dataframe

我创建了一个数据框data,它是各个列的串联,如下所示:

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)

结果:

                         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

现在,我想在gapMIP列之间的obj下插入新列t(ms)。我该怎么办?

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

1 个答案:

答案 0 :(得分:1)

使用元组在MultiIndex中分配值,对于新的第六列,也必须将1更改为6

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