Python 在熊猫中使用concat函数
我想合并df1和df2。 我使用了带有外部连接的concat函数,并使用了多索引Python 在熊猫中使用concat函数,python,pandas,Python,Pandas,我想合并df1和df2。 我使用了带有外部连接的concat函数,并使用了多索引 Desired result would be : U-01 U-02 U-03 U-04 U-05 LEVEL H L H M L STANDARD 3 3 3 3 2
Desired result would be :
U-01 U-02 U-03 U-04 U-05
LEVEL H L H M L
STANDARD 3 3 3 3 2
L1 A 3.0 3.0 3.0 3.0 3.0
L2 B 3.0 3.0 3.0 3.0 3.0
L3 C 3.0 3.0 3.0 3.0 3.0
L4 D 3.0 3.0 3.0 3.0 3.0
index = INDEX, host
结果是合并的索引值,我要分割索引列
请告诉我怎么做
df1:
CODE U-01 U-02 U-03 U-04 U-05
INDEX host
L1 A 3.0 3.0 3.0 3.0 3.0
L2 B 3.0 3.0 3.0 3.0 3.0
L3 C 3.0 3.0 3.0 3.0 3.0
L4 D 3.0 3.0 3.0 3.0 3.0
df2:
CODE U-01 U-02 U-03 U-04 U-05
LEVEL H L H M L
STANDARD 3 3 3 3 2
所以,我的代码是
total_data = pd.concat([df1, df2], join='outer')
但是,结果是
U-01 U-02 U-03 U-04 U-05
LEVEL H L H M L
STANDARD 3 3 3 3 2
(L1,A) 3.0 3.0 3.0 3.0 3.0
(L2,B) 3.0 3.0 3.0 3.0 3.0
(L3,C) 3.0 3.0 3.0 3.0 3.0
(L4,D) 3.0 3.0 3.0 3.0 3.0
我想拆分列并使用多索引
Desired result would be :
U-01 U-02 U-03 U-04 U-05
LEVEL H L H M L
STANDARD 3 3 3 3 2
L1 A 3.0 3.0 3.0 3.0 3.0
L2 B 3.0 3.0 3.0 3.0 3.0
L3 C 3.0 3.0 3.0 3.0 3.0
L4 D 3.0 3.0 3.0 3.0 3.0
index = INDEX, host
在concat之前,您需要在两个数据帧中的索引中使用多索引 因此,请使用:
df2 = df2.assign(new = '').set_index('new', append=True)
total_data = pd.concat([df1, df2])
然后第二层被第二层中的空格填充(这是一个小把戏,因为看不见它)
也可以为第二级添加一些值(现在可以看到,有值<代码>新建代码>):
什么是print(df1.index.tolist())
,print(df1.columns.tolist())
,print(df2.index.tolist())
,print(df2.columns.tolist())
?df1.index:多索引[(L1,A],(L2,B),(L3,C),(L4,D)]
df1.列:索引['U-01',U-02',U-03',U-04',U-05]
index:['LEVEL','STANDARD']
df2.列:索引['U-01',U-02',U-03',U-04',U-05']