我创建了一个数据框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
现在,我想在gap
和MIP
列之间的obj
下插入新列t(ms)
。我该怎么办?
gap=(data['LP']['obj']-data['MIP']['obj'])/data['MIP']['obj']
data['MIP'].insert(1,'gap',gap) #this doesn't work
答案 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