在熊猫中设置多列索引

发布于 2021-01-29 15:06:23

我这样制作数据框。

df = pd.DataFrame({
    'class' : ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'],
    'number' : [1,2,3,4,5,1,2,3,4,5],
    'math' : [90, 20, 50, 30, 57, 67, 89, 79, 45, 23],
    'english' : [40, 21, 68, 89, 90, 87, 89, 54, 21, 23]
})

我想通过使用一些熊猫方法将索引转换为此(例如set_index,stack 、、)

df1 = pd.DataFrame(np.random.randint(1, 100, (5, 4)),
             columns = [['A', 'A', 'B', 'B'],['english', 'math', 'english', 'math']],
             index = [1, 2, 3, 4, 5])

我怎样才能做到这一点?

关注者
0
被浏览
75
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    我认为你需要set_indexunstack重塑,然后交换在水平MultiIndex由列swaplevel由去年的排序列sort_index

    df1 = df.set_index(['number','class']).unstack().swaplevel(0,1,1).sort_index(1)
    
    print (df1)
    class        A            B     
           english math english math
    number                          
    1           40   90      87   67
    2           21   20      89   89
    3           68   50      54   79
    4           89   30      21   45
    5           90   57      23   23
    

    用另一种解决方案stackunstack

    print (df.set_index(['number','class']).stack().unstack([1,2]))
    class        A            B     
           english math english math
    number                          
    1           40   90      87   67
    2           21   20      89   89
    3           68   50      54   79
    4           89   30      21   45
    5           90   57      23   23
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看