将多索引列转换为标准列

Nyx*_*nyx 3 python multi-index python-3.x pandas

我们如何转换包含 MultiIndex 列的 Pandas DataFrame,例如

                FB                  AAPL
                open    volume      open    volume
date
2019-10-30      189.56  28734995    244.76  31130522
2019-10-31      196.70  42286529    247.24  34790520
2019-11-01      192.85  21711829    249.54  37781334
Run Code Online (Sandbox Code Playgroud)

到一个具有常规列的索引,其中索引级别之一现在是所有行中的一列

                open    volume      ticker  
date
2019-10-30      189.56  28734995    FB      
2019-10-31      196.70  42286529    FB      
2019-11-01      192.85  21711829    FB      
2019-10-30      244.76  31130522    AAPL
2019-10-31      247.24  34790520    AAPL
2019-11-01      249.54  37781334    AAPL
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 5

主要思想是使用DataFrame.stackwithDataFrame.reset_index将 MultiIndex 第二级转换为列:

df = df.stack(0).rename_axis(('date','ticker')).reset_index(level=1)
print (df)
           ticker    open    volume
date                               
2019-10-30   AAPL  244.76  31130522
2019-10-30     FB  189.56  28734995
2019-10-31   AAPL  247.24  34790520
2019-10-31     FB  196.70  42286529
2019-11-01   AAPL  249.54  37781334
2019-11-01     FB  192.85  21711829
Run Code Online (Sandbox Code Playgroud)

如果排序很重要,则使用ordered catagoricals 进行代码、排序以及将列重新分配到最后一个位置DataFrame.pop

df1 = df.stack(0).rename_axis(('date','ticker')).reset_index(level=1)
df1['ticker'] = pd.Categorical(df1.pop('ticker'), 
                               ordered=True, 
                               categories=df.columns.get_level_values(0).unique())
df1 = df1.sort_values(['ticker','date'])
print (df1)
              open    volume ticker
date                               
2019-10-30  189.56  28734995     FB
2019-10-31  196.70  42286529     FB
2019-11-01  192.85  21711829     FB
2019-10-30  244.76  31130522   AAPL
2019-10-31  247.24  34790520   AAPL
2019-11-01  249.54  37781334   AAPL
Run Code Online (Sandbox Code Playgroud)