如何在 pandas 中创建多级数据框? [英] How to create a multilevel dataframe in pandas?

查看:45
本文介绍了如何在 pandas 中创建多级数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定两个不同的 df:

Given two different df's:

'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'

            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 是一个数据时间"对象

*index is a 'datatime' object

谢谢

推荐答案

一种选择是使用 MultiIndex()A 构建列级别B 然后将它们连接起来:

One option is to use MultiIndex() to construct the columns level for A and B and then concatenate them:

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

这篇关于如何在 pandas 中创建多级数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆