【问题标题】:What are the levels in multi index data frame called?多索引数据框中的级别是什么?
【发布时间】:2021-08-31 12:01:11
【问题描述】:

对于名为的多索引数据框,我的图片上有哪些不同级别?以及如何使用 pivot_table 访问每个级别。

另外,我如何在日期上方添加“Ticker”

【问题讨论】:

  • 通过tuple() 例如df.loc[:,('Close','A')]
  • 你有多个索引列......所以黄色部分是level0,黑色部分是level1

标签: python pandas multi-index


【解决方案1】:

层级从01等开始命名,最上层为0

您可以通过pandas.MultiIndex.get_level_values 访问每个级别。例如,您可以使用以下内容来获取您想要的列索引的级别1(从顶部开始的第二级):

df.columns.get_level_values(1)

【讨论】:

    【解决方案2】:

    你有多个索引列......所以黄色部分是level 0,黑色部分是level 1

    所以如果你想访问值然后使用(例如):

    df.loc[:,('Close','A')]    #for selecting a single column
    #OR
    df.loc[:, df.columns.get_level_values(1)=='A']  #for selecting all values at level 1 where column is 'A'
    #OR
    df.loc[:, df.columns.get_level_values(0)=='Close']  #for selecting all values at level 0 where column is 'Close'
    

    如果要创建单级索引,则必须删除 level 0level 1

    df=df.droplevel(0,1)  #for removing the columns name in yellow part
    #OR
    df=df.droplevel(1,1)  #for removing the columns name in black part
    

    如果您不想失去任何级别,那么您可以将这 2 个级别合并为一个级别,以便您可以像往常一样访问列:

    df.columns=df.columns.map('_'.join)
    #here the both level is joined by '_' btw you can use any custum character for joining levels
    

    更多信息请参考documentation

    This article 也可能有帮助

    【讨论】:

      猜你喜欢
      • 2018-04-20
      • 1970-01-01
      • 1970-01-01
      • 2013-12-04
      • 2018-10-24
      • 2018-08-24
      • 2015-01-22
      • 2013-06-09
      相关资源
      最近更新 更多