如何在Pandas中的多个索引下重新排序列

时间:2015-12-15 07:25:21

标签: python pandas

我有以下数据:

Set Adjuvant    Route   Organ   Up  Down
set7    FOO ID  LV  11  14
set7    BAR ID  LV  17  15
set7    QUX ID  LV  10  22
set7    FOO ID  SP  14  13
set7    BAR ID  SP  13  8
set7    QUX ID  SP  11  18
set7    FOO ID  LN  25  25
set7    BAR ID  LN  38  16
set7    QUX ID  LN  53  18

我已阅读并使用以下代码重新组织它:

import pandas as pd 
df = pd.io.parsers.read_table("http://dpaste.com/3QB2YQX.txt")
df = df.pivot(index="Adjuvant",columns="Organ")

# Remove unwanted index name
df.drop('Set',axis=1,inplace=True)
df.drop('Route',axis=1,inplace=True)
df.index.name = None
df.columns.names = (None,None)

ndf = df.reindex(sorted(df.index, key=lambda x: x.lower()))

这构成了这个数据框:

In [35]: ndf
Out[35]:
     Up         Down
     LN  LV  SP   LN  LV  SP
BAR  38  17  13   16  15   8
FOO  25  11  14   25  14  13
QUX  53  10  11   18  22  18

我想要做的是将UP/DOWN索引下的列从LN, LV, SP呈现为LV, SP, LN。我该怎么办?

1 个答案:

答案 0 :(得分:2)

使用set_levels

In [3]: ndf[ndf.columns.set_levels(['LV', 'SP','LN'], level=1)]
Out[3]:
     Up         Down
     LV  SP  LN   LV  SP  LN
BAR  17  13  38   15   8  16
FOO  11  14  25   14  13  25
QUX  10  11  53   22  18  18

这在网站上没有文档,没有专门的页面,但如果你做一个tab-lookup来显示docstring,它会显示:

Signature: ndf.columns.set_levels(levels, level=None, inplace=False, verify_integrity=True)
Docstring:
Set new levels on MultiIndex. Defaults to returning
new index.

Parameters
----------
levels : sequence or list of sequence
    new level(s) to apply
level : int or level name, or sequence of int / level names (default None)
    level(s) to set (None for all levels)
inplace : bool
    if True, mutates in place
verify_integrity : bool (default True)
    if True, checks that levels and labels are compatible

Returns
-------
new index (of same type and class...etc)


Examples
--------
>>> idx = MultiIndex.from_tuples([(1, u'one'), (1, u'two'),
                                  (2, u'one'), (2, u'two')],
                                  names=['foo', 'bar'])
>>> idx.set_levels([['a','b'], [1,2]])
MultiIndex(levels=[[u'a', u'b'], [1, 2]],
           labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
           names=[u'foo', u'bar'])
>>> idx.set_levels(['a','b'], level=0)
MultiIndex(levels=[[u'a', u'b'], [u'one', u'two']],
           labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
           names=[u'foo', u'bar'])
>>> idx.set_levels(['a','b'], level='bar')
MultiIndex(levels=[[1, 2], [u'a', u'b']],
           labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
           names=[u'foo', u'bar'])
>>> idx.set_levels([['a','b'], [1,2]], level=[0,1])
MultiIndex(levels=[[u'a', u'b'], [1, 2]],
           labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
           names=[u'foo', u'bar'])
File:      c:\winpython-64bit-3.4.3.5\python-3.4.3.amd64\lib\site-packages\pandas\core\index.py
Type:      method