Pandas 分层数据框架

5

I have a dataframe:

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
1个回答

14

假设 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

1
非常感谢。运行得非常顺利。 - root
1
请问您能否解释一下这个答案或提供相关文档链接? - Mike

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接