如何将数据框的一个列名(层次结构)移动到索引?

huangapple go评论62阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年7月17日 17:47:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76703233.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定