在 pandas 中设置多列索引 [英] Set multi column index in pandas

查看:136
本文介绍了在 pandas 中设置多列索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这样制作数据框.

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,...)

and i want to convert index to this by using some pandas methods.(ex. 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])

我该怎么做?

推荐答案

我认为您需要MultiIndex中的级别. swaplevel.html"rel =" noreferrer> swaplevel 并按

I think you need set_index with unstack for reshaping, then swap levels in MultiIndex in columns by swaplevel and last sort columns by 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

使用 stack 的另一种解决方案和 unstack :

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

这篇关于在 pandas 中设置多列索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆