给出两个不同的df:
' A'
a b
2016-11-21 2 1
2016-11-22 3 4
2016-11-23 5 2
2016-11-24 6 3
2016-11-25 6 3
' B'
a b
2016-11-21 3 0
2016-11-22 1 0
2016-11-23 1 6
2016-11-24 1 5
2016-11-25 0 2
如何创建多层次'这种形状的数据框:
' C'
A B
a b a b
2016-11-21 2 1 3 0
2016-11-22 3 4 1 0
2016-11-23 5 2 1 6
2016-11-24 6 3 1 5
2016-11-25 6 3 0 2
* index是一个'数据时间'对象
由于
答案 0 :(得分:6)
一种方法是使用MultiIndex()
构建A
和B
的列级别,然后将它们连接起来:
import pandas as pd
A.columns = pd.MultiIndex.from_product([['A'], A.columns])
B.columns = pd.MultiIndex.from_product([['B'], B.columns])
pd.concat([A, B], axis = 1)
# A B
# a b a b
#2016-11-21 2 1 3 0
#2016-11-22 3 4 1 0
#2016-11-23 5 2 1 6
#2016-11-24 6 3 1 5
#2016-11-25 6 3 0 2
答案 1 :(得分:6)
您可以将concat
与参数keys
:
df = pd.concat([A, B], axis = 1, keys=(list('AB')))
print (df)
A B
a b a b
2016-11-21 2 1 3 0
2016-11-22 3 4 1 0
2016-11-23 5 2 1 6
2016-11-24 6 3 1 5
2016-11-25 6 3 0 2