Ordering hierarchical data in a pivot-like way

Viewed 82

I have a hierarchical dataset which needs to be presented in a certain way. Items of the same hierarchy paths needs to be presented in successive order. Further parents should be listed above their children.
Appreciate any guidance to achieve the same..

Thank You

** sample dataset **

level   Parent  Child
0   z   z
1   z   o
1   z   p
2   p   t
2   p   q
2   o   r

** what i tried **

df = pd.read_clipboard(sep='\t')
df1=df.pivot(columns='level',values='Child')
df1.fillna('-',inplace=True)
df1

** my result **

level   0   1   2
0   z   -   -
1   -   o   -
2   -   p   -
3   -   -   t
4   -   -   q
5   -   -   r

** desired result **

level   0   1   2
0   z   -   -
1   -   o   -
2   -   -   r
3   -   p   -
4   -   -   t
5   -   -   q
1 Answers

As the title states that the question is about hierarchies, the solution is should be found in some network packages like networkx or igraph. I am not an expert in that tools, so I give an abstract solution to this question.

The writer of the question is asking for an order based on the way to the given item, e.g. going from a parent downwards the stream to the children. So the following workflow is appropriate.

  1. find for each item the path from the top level to this item. (example: the last item in the list z -> p -> q)
  2. Order the paths (key from top level to low level)
  3. Apply the order onto the pivoted table
Related