Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python/pandas:如何使用分层列索引将两个数据帧合并为一个?_Python_Pandas - Fatal编程技术网

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

python/pandas:如何使用分层列索引将两个数据帧合并为一个?,python,pandas,Python,Pandas,我有两个数据帧,如下所示: >>> 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 我如何用下面的分层列索引从这两个数据帧中生成一个数据帧

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

>>> 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
我如何用下面的分层列索引从这两个数据帧中生成一个数据帧

            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
这是一个文档示例:


,只需将密钥的dict-to-pieces传递给ConcatMe它将dfs作为密钥如果您只想添加数据帧名称作为第一级:pd.concat(dict(df1=df1),axis=1)@Mr_and_-Mrs_D,它不将
pd.DataFrames
作为密钥。内置的
dict()
构造函数,允许使用关键字参数设置简单的字符串键。python文档中的示例是:
dict(sape=4139,guido=4127,jack=4098)
。这就是为什么调用
pd.concat()后,
'df1'
'df2'
是键的原因。
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