Multiindex在表格的右侧打印第二级索引标签

时间:2016-07-04 15:01:19

标签: python pandas

http://pandas.pydata.org/pandas-docs/stable/advanced.html

为例
In [10]: arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']),
   ....:           np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]
   ....: 

In [11]: s = pd.Series(np.random.randn(8), index=arrays)

In [13]: df = pd.DataFrame(np.random.randn(8, 4), index=arrays)

In [14]: df
Out[14]: 
                0         1         2         3
bar one -0.424972  0.567020  0.276232 -1.087401
    two -0.673690  0.113648 -1.478427  0.524988
baz one  0.404705  0.577046 -1.715002 -1.039268
    two -0.370647 -1.157892 -1.344312  0.844885
foo one  1.075770 -0.109050  1.643563 -1.469388
    two  0.357021 -0.674600 -1.776904 -0.968914
qux one -1.294524  0.413738  0.276662 -0.472035
    two -0.013960 -0.362543 -0.006154 -0.923061

如何在最后一列之后移动第二个索引打印显示? 像这样:

            0         1         2         3
bar -0.424972  0.567020  0.276232 -1.087401 one
    -0.673690  0.113648 -1.478427  0.524988 two
baz  0.404705  0.577046 -1.715002 -1.039268 one
    -0.370647 -1.157892 -1.344312  0.844885 two
foo  1.075770 -0.109050  1.643563 -1.469388 one
     0.357021 -0.674600 -1.776904 -0.968914 two
qux -1.294524  0.413738  0.276662 -0.472035 one
    -0.013960 -0.362543 -0.006154 -0.923061 two

1 个答案:

答案 0 :(得分:1)

不完全相同,但您可以调用reset_index传递第二级,然后使用ix使用花式索引重新排序列并传递所需列顺序的列表:

In [100]:
df.reset_index(level=1).ix[:,list(df) + ['level_1']]

Out[100]:
            0         1         2         3 level_1
bar -0.171917 -0.084470  0.568098  0.749653     one
bar  0.114017  0.474004 -0.032003  0.197596     two
baz -0.310686 -0.236696  0.471586 -0.286288     one
baz  2.014078  0.957119 -0.399487  1.109984     two
foo -0.309654  0.916766  1.207385 -0.673540     one
foo  0.442063 -0.819095  0.314201 -1.125304     two
qux  1.817970 -0.316869  1.773183 -0.097240     one
qux  0.025067  0.135640  1.054219 -0.230144     two