python/pandas:如何将两个数据帧与分层列索引合并为一个?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15989281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 20:46:10  来源:igfitidea点击:

python/pandas: how to combine two dataframes into one with hierarchical column index?

pythonpandas

提问by behzad.nouri

I have two dataframes which look like this:

我有两个数据框,如下所示:

>>> df1
              A    B
2000-01-01  1.4  1.4
2000-01-02  1.7 -1.9
2000-01-03 -0.2 -0.8

>>> df2
              A    B
2000-01-01  0.6 -0.3
2000-01-02 -0.4  0.6
2000-01-03  1.1 -1.0

How can I make one dataframe out of this two with hierarchical column index like below?

如何使用如下所示的分层列索引从这两个数据帧中创建一个数据帧?

            df1       df2
              A    B    A    B
2000-01-01  1.4  1.4  0.6 -0.3
2000-01-02  1.7 -1.9 -0.4  0.6
2000-01-03 -0.2 -0.8  1.1 -1.0

采纳答案by Jeff

This is a doc example: http://pandas.pydata.org/pandas-docs/stable/merging.html#more-concatenating-with-group-keys

这是一个文档示例:http: //pandas.pydata.org/pandas-docs/stable/merging.html#more-concatenating-with-group-keys

In [9]: df1 = pd.DataFrame(np.random.randn(3,2),columns=list('AB'),index=pd.date_range('20000101',periods=3))

In [10]: df2 = pd.DataFrame(np.random.randn(3,2),columns=list('AB'),index=pd.date_range('20000101',periods=3))

In [11]: df1
Out[11]: 
                   A         B
2000-01-01  0.129994  1.189608
2000-01-02 -1.126812  1.087617
2000-01-03 -0.930070  0.253098

In [12]: df2
Out[12]: 
                   A         B
2000-01-01  0.535700 -0.769533
2000-01-02 -1.698531 -0.456667
2000-01-03  0.451622 -1.500175

In [13]: pd.concat(dict(df1 = df1, df2 = df2),axis=1)
Out[13]: 
                 df1                 df2          
                   A         B         A         B
2000-01-01  0.129994  1.189608  0.535700 -0.769533
2000-01-02 -1.126812  1.087617 -1.698531 -0.456667
2000-01-03 -0.930070  0.253098  0.451622 -1.500175