pandas 如何在熊猫中创建多级数据框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40820017/
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-14 02:31:00  来源:igfitidea点击:

How to create a multilevel dataframe in pandas?

pythonpython-2.7pandasdataframemulti-level

提问by hernanavella

Given two different df's:

给定两个不同的 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

How can I create a 'multilevel' dataframe of this shape:

如何创建这种形状的“多级”数据框:

'C'

'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 is a 'datatime' object

*index 是一个“数据时间”对象

Thanks

谢谢

采纳答案by Psidom

One option is to use MultiIndex()to construct the columns level for Aand Band then concatenate them:

一种选择是使用MultiIndex()构造柱水平AB,然后将它们连接起来:

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

回答by jezrael

You can use concatwith parameter keys:

您可以使用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