title: Parent | Child DataFrame to balanced Hierarchy
body: <p>I'm attempting to take a Data Frame with two columns, a Parent and Child and effectively 'flatten' it.</p>
  
  <p>Input</p>
  
  <pre><code>Parent | Child
  A         B
  A         C
  C         D
  D         E
  B         T
  </code></pre>
  
  <p>Output</p>
  
  <pre><code>level0 | level1 | level2 | level3
  A         B         T
  A         C         D        E
  </code></pre>
  
  <p>the only methods i've been able to figure out thus far is converting the DataFrame to a list of tuples and running something like this:</p>
  
  <pre><code>test = []
  parents = set()
  children = {}
  for c,p in ancestry2:
      #print(c,p)
      parents.add(p)
      children[c] = p
  
  # recursively determine parents until child has no parent
  def ancestors(p):
      return (ancestors(children[p]) if p in children else []) + [p]
  
  # for each child that has no children print the geneology
  for k in (set(children.keys()) - parents):
      #print(k)
      test.append(ancestors(k))
      print('/'.join(ancestors(k)))
  </code></pre>
  
  <p>but this results in "RecursionError: maximum recursion depth exceeded" and if i increase the recursion limit obviously Python crashes.  I'm dealing with &lt;100k records in total.</p>
  
  <p>Any thoughts?  Is there a better way to 'flatten' a parent child relationship?</p>
  
  <p>I suppose it would be easier to move this over to SQL and use a CTE to achieve the desired effect.. but i'd like to learn how to do this in Python.</p>