Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas hierarchical dataframe

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

Is there a way to greate a "nested" hierarchical index like this:

Form nr Element Type    Text    Options
   1    Name1   select  text1   op1
                                op2
                                op3
        Name2   input   text2   NaN
   2    Name1   input   text2   NaN
like image 618
root Avatar asked Sep 26 '12 08:09

root


People also ask

How do I create a hierarchical index in pandas?

To make the column an index, we use the Set_index() function of pandas. If we want to make one column an index, we can simply pass the name of the column as a string in set_index(). If we want to do multi-indexing or Hierarchical Indexing, we pass the list of column names in the set_index().

What is a MultiIndex Dataframe?

MultiIndex is an array of tuples where each tuple is unique. You can create MultiIndex from list of arrays, arry of tuples, dataframe e.t.c. The Index constructor will attempt to return a MultiIndex when it is passed a list of tuples. You can have Multi-level for both Index and Column labels.

Why do pandas use hierarchical index?

Using Hierarchical Indexing in Code This extra syntax allows for greater flexibility when creating queries that cover large, complex DataFrames. These are some basic examples of how to code and utilize DataFrames within Panda.


1 Answers

Assuming there is a typo in the Text column, text <-> text1? I`ll go from your first 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
like image 55
Wouter Overmeire Avatar answered Oct 05 '22 13:10

Wouter Overmeire