2017-04-07 58 views
1

如果df是熊猫数据框与对行的5级多指标,是有一个多少有点愚蠢的方式来实现由此产生的顺序排序?如何多索引行

NB:所有与由表达上述制作不同以下产品排序的:

df.sortlevel([4, 1, 0, 2, 3], sort_remaining=False) 
df.sortlevel([4, 1, 0, 2, 3], sort_remaining=True) 
df.sortlevel([3, 2, 0, 1, 4], sort_remaining=False) 
df.sortlevel([3, 2, 0, 1, 4], sort_remaining=True) 
+0

@pansen:没有,我查;我已更新我的帖子以清楚说明。 – kjo

回答

1

是!不要使用sortlevel。使用sort_indexlevel=[4, 1, 0, 2, 3]

考虑数据框df

from string import ascii_uppercase 
import pandas as pd 

f = lambda n: np.random.choice(list(ascii_uppercase), n, False) 
mux = pd.MultiIndex.from_product([f(2) for _ in range(5)]) 
df = pd.Series(range(32), mux, name='One').to_frame() 
print(df) 

      One 
T B W G U 0 
     P 1 
     M U 2 
     P 3 
    G G U 4 
     P 5 
     M U 6 
     P 7 
    V W G U 8 
     P 9 
     M U 10 
     P 11 
    G G U 12 
     P 13 
     M U 14 
     P 15 
R B W G U 16 
     P 17 
     M U 18 
     P 19 
    G G U 20 
     P 21 
     M U 22 
     P 23 
    V W G U 24 
     P 25 
     M U 26 
     P 27 
    G G U 28 
     P 29 
     M U 30 
     P 31 

然后排序

df.sort_index(level=[4, 1, 0, 2, 3]) 

      One 
R B G G P 21 
    V G G P 29 
    B G M P 23 
    V G M P 31 
    B W G P 17 
    V W G P 25 
    B W M P 19 
    V W M P 27 
T B G G P 5 
    V G G P 13 
    B G M P 7 
    V G M P 15 
    B W G P 1 
    V W G P 9 
    B W M P 3 
    V W M P 11 
R B G G U 20 
    V G G U 28 
    B G M U 22 
    V G M U 30 
    B W G U 16 
    V W G U 24 
    B W M U 18 
    V W M U 26 
T B G G U 4 
    V G G U 12 
    B G M U 6 
    V G M U 14 
    B W G U 0 
    V W G U 8 
    B W M U 2 
    V W M U 10 

既然你排序的所有级别,没有必要为sort_remaining=False