【问题标题】:Pandas hierarchical dataframe熊猫分层数据框
【发布时间】:2012-09-17 20:30:30
【问题描述】:

我有一个数据框:

Form nr Element Type    Text    Options
   1    Name1   select  text1   op1
   1    Name1   select  text    op2
   1    Name1   select  text    op3
   1    Name2   input   text2   NaN
   2    Name1   input   text2   NaN

有没有办法像这样增加“嵌套”层次索引:

Form nr Element Type    Text    Options
   1    Name1   select  text1   op1
                                op2
                                op3
        Name2   input   text2   NaN
   2    Name1   input   text2   NaN

【问题讨论】:

    标签: python dataframe pandas


    【解决方案1】:

    假设 Text 列中有错字, text text1? 我会从你的第一个 DataFrame 开始。

    In [11]: df
    Out[11]: 
       Form nr Element    Type   Test Options
    0     1      Name1  select  text1     op1
    1     1      Name1  select   text     op2
    2     1      Name1  select   text     op3
    3     1      Name2   input  text2     NaN
    4     2      Name1   input  text2     NaN
    
    In [12]: df.set_index(['Form', 'nr Element', 'Type', 'Test'])
    Out[12]: 
                                 Options
    Form nr Element Type   Test         
    1    Name1      select text1     op1
                           text      op2
                           text      op3
         Name2      input  text2     NaN
    2    Name1      input  text2     NaN
    

    【讨论】:

    • 非常感谢。像魅力一样工作。
    • 您能否解释一下这个答案或相关文档的链接?
    猜你喜欢
    • 2018-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 2022-01-12
    • 2013-06-23
    相关资源
    最近更新 更多