在熊猫中设置多列索引
发布于 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 个回答
-
我认为你需要
set_index
与unstack
重塑,然后交换在水平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
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