重塑多索引 pandas 数据框 [英] Reshaping a multiindex pandas dataframe

查看:59
本文介绍了重塑多索引 pandas 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的多索引熊猫数据框

I have a multiindex pandas dataframe that looks like this

 ID            I                   II                  III
 METRIC        a    b    c    d    a    b    c    d    a    b    c    d
 2015-08-01    0    1    2    3    20   21   22   23   40   41   42   43
 2015-08-02    4    5    6    7    24   25   26   27   44   45   46   47
 2015-08-03    8    9    10   11   28   29   30   31   48   49   50   51

,其中按日期(2015-08-012015-08-022015-08-03等)索引,第一级列(IIIIII)是ID s第二级列是对应的METRIC(abcd).我想将其重塑为以下内容

where it is indexed by the dates (2015-08-01, 2015-08-02, 2015-08-03, etc.), the first-level columns (I, II, III) are IDs and the second-level columns are corresponding METRICs (a, b, c, d). I would like to reshape it to the following

METRIC               a    b    c    d
ID
I      2015-08-01    0    1    2    3
       2015-08-02    4    5    6    7
       2015-08-03    8    9    10   11
II     2015-08-01    20   21   22   23
       2015-08-02    24   25   26   27
       2015-08-03    28   29   30   31
III    2015-08-01    40   41   42   43
       2015-08-02    44   45   46   47
       2015-08-03    48   49   50   51

我(未成功)调查了使用.pivot.stack.melt的情况,但是它们没有给我我想要的东西.我目前遍历ID s并建立一个数据框的列表,然后将它们concat一起作为新的数据框来获得我想要的.

I have (unsuccessfully) looked into using .pivot, .stack, and .melt, but they don't give me what I am looking for. I currently loop over IDs and build a list of dataframes and concat them together as a new dataframe to get what I want.

任何建议将不胜感激.

推荐答案

让我们使用stackswaplevelsort_index:

df.stack(0).swaplevel(0,1).sort_index()

输出:

METRIC           a   b   c   d
ID                            
I   2015-08-01   0   1   2   3
    2015-08-02   4   5   6   7
    2015-08-03   8   9  10  11
II  2015-08-01  20  21  22  23
    2015-08-02  24  25  26  27
    2015-08-03  28  29  30  31
III 2015-08-01  40  41  42  43
    2015-08-02  44  45  46  47
    2015-08-03  48  49  50  51

这篇关于重塑多索引 pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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