gpt4 book ai didi

python - 在 Pandas 中设置多列索引

转载 作者:太空狗 更新时间:2023-10-29 18:22:42 29 4
gpt4 key购买 nike

我像这样制作数据框。

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]
})

我想使用一些 pandas 方法将索引转换为此。(例如 set_index、堆栈、、、)

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])

我该怎么做?

最佳答案

我想你需要set_indexunstack用于 reshape ,然后按 swaplevel 交换列中 MultiIndex 中的级别最后按 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

关于python - 在 Pandas 中设置多列索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41208610/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com