熊猫,如何将列添加到多索引列DataFrame

cnc*_*gvg 6 python pandas

这是我原始的DataFrame(带有multiindex列):

In [72]:df
Out[72]: 
          a                   b          
          x         y         x         y
0  1.545293 -0.459270  0.899254 -1.010453
1  0.458760  0.275400 -0.190951  0.169195
2 -0.941817  1.109823  0.077953 -0.247074
3  1.790101 -1.643470  0.979625 -1.704657
4 -2.044814 -0.243726 -0.039724  0.600066
Run Code Online (Sandbox Code Playgroud)

我还有另一个DataFrame:

In [77]:df2
Out[77]: 
          x         y
0 -1.085869 -0.952949
1  0.601585  0.570050
2  0.328601  0.802610
3 -0.415952 -0.090088
4  0.757545 -0.736933
Run Code Online (Sandbox Code Playgroud)

我该如何添加df2的列df以获取像这样的新DataFrame:

In [83]:df3
Out[83]: 
          a                   b                   c          
          x         y         x         y         x         y
0  1.545293 -0.459270  0.899254 -1.010453 -1.085869 -0.952949
1  0.458760  0.275400 -0.190951  0.169195  0.601585  0.570050
2 -0.941817  1.109823  0.077953 -0.247074  0.328601  0.802610
3  1.790101 -1.643470  0.979625 -1.704657 -0.415952 -0.090088
4 -2.044814 -0.243726 -0.039724  0.600066  0.757545 -0.736933
Run Code Online (Sandbox Code Playgroud)

我当前的方法是使用for循环:

for col in df2.columns:
    df['c', col] = df2[col]
Run Code Online (Sandbox Code Playgroud)

有什么方法可以避免循环吗?

Kar*_*tik 1

Try pd.concat:

pieces = {'a' : df1['a'],
          'b' : df1['b'],
          'c' : df2}
df3 = pd.concat(pieces, axis=1)
Run Code Online (Sandbox Code Playgroud)