英文:
how to move dataframe's one column names(hierarchical) to index?
问题
抱歉,这似乎是一个基本的操作,但我在搜索后还是弄不明白。标题可能不准确。
我有这个数据框:
Bunker Port Rotterdam Singapore ... Rotterdam Singapore
bunker HSFO HSFO ... VLSFO VLSFO
period ...
Jul 23 453.318000 461.028000 ... 518.098000 553.426000
Aug 23 448.266000 454.016000 ... 513.596000 549.716000
列名有两个级别:'Bunker Port' 和 'bunker'
我希望将数据框转换成以下形式(0-4索引部分不必要):
bunker HSFO MGO VLSFO
0 period Bunker Port NaN NaN NaN
1 Jul 23 Rotterdam 453.318 723.83300 518.098
2 Aug 23 Rotterdam 448.266 735.00000 513.596
3 Jul 23 Singapore 461.028 734.04850 553.426
4 Aug 23 Singapore 454.016 738.74945 549.716
非常感谢。
英文:
I am sorry this seems a basic manipulation but I can't figure it out after searching. The title is probably not accurate.
I have this dataframe
Bunker Port Rotterdam Singapore ... Rotterdam Singapore
bunker HSFO HSFO ... VLSFO VLSFO
period ...
Jul 23 453.318000 461.028000 ... 518.098000 553.426000
Aug 23 448.266000 454.016000 ... 513.596000 549.716000
There are 2 levels for the column names: 'Bunker Port' and 'bunker'
and I wish to convert the df to below(the 0-4 index is unecessary):
bunker HSFO MGO VLSFO
0 period Bunker Port NaN NaN NaN
1 Jul 23 Rotterdam 453.318 723.83300 518.098
2 Aug 23 Rotterdam 448.266 735.00000 513.596
3 Jul 23 Singapore 461.028 734.04850 553.426
4 Aug 23 Singapore 454.016 738.74945 549.716
Thanks a lot
答案1
得分: 1
你应该使用stack()
函数将Bunker Port
列索引作为行索引移动,然后可以使用reset_index()
函数来重置索引并将MultiIndex级别转换为单独的列。
df.stack().reset_index()
你也可以在stack()
函数内指定级别:
df.stack(level=[0, 1]).reset_index()
英文:
You should use the stack()
function to move the Bunker Port
column index as a row index and then you can use reset_index()
function to reset the index and convert the MultiIndex levels into separate columns.
df.stack().reset_index()
You can also specify the level inside the stack()
function:
df.stack(level=[0, 1]).reset_index()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论