多重索引的滚动级别

2024-10-04 15:30:32 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个数据帧,其中我的列是一个多索引

col = pd.MultiIndex.from_product(
    [[1, 2], ['A', 'B'], ['First', 'Second']],
    names=['Cat', 'Dog', 'Bird']
)
dat = np.arange(16).reshape(2, -1)
df = pd.DataFrame(dat, columns=col)
df

Cat      1                         2                    
Dog      A            B            A            B       
Bird First Second First Second First Second First Second
0        0      1     2      3     4      5     6      7
1        8      9    10     11    12     13    14     15

我想调整列,使Bird级别位于顶部,Cat级别向下移动到中间,Dog向下移动到底部。你知道吗

尝试1

使用swaplevel可以连续使用,但是在中间创建一个完整的数据帧只是为了增加列,感觉很笨拙。你知道吗

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

Bird First             Second            
Cat      1       2          1       2    
Dog      A   B   A   B      A   B   A   B
0        0   2   4   6      1   3   5   7
1        8  10  12  14      9  11  13  15

尝试2

创建新的MultiIndex应该是高效的,但是没有那么直观,可能会有不必要的冗长。你知道吗

def roll(x):
    return x[-1:] + x[:-1]

df.set_axis(
    pd.MultiIndex.from_tuples(
        [roll(x) for x in df.columns.values],
        names=roll(df.columns.names)
    ), axis=1, inplace=False).sort_index(1)

Bird First             Second            
Cat      1       2          1       2    
Dog      A   B   A   B      A   B   A   B
0        0   2   4   6      1   3   5   7
1        8  10  12  14      9  11  13  15

问题

有没有一种干净直观的方法来做到这一点,而不必在中间创建一个中间数据帧?你知道吗


Tags: columns数据fromdfnamescolcatfirst
1条回答
网友
1楼 · 发布于 2024-10-04 15:30:32

先生,这是您需要的吗?使用^{}

df.reorder_levels(['Bird','Cat','Dog'],axis=1).sort_index(level=0,axis=1)
Out[396]: 
Bird First             Second            
Cat      1       2          1       2    
Dog      A   B   A   B      A   B   A   B
0        0   2   4   6      1   3   5   7
1        8  10  12  14      9  11  13  15

相关问题 更多 >

    热门问题