Identifying root parents and all their children in trees

BKS*_*BKS 11 python pandas

I have a pandas dataframe as such:

parent   child   parent_level   child_level
A        B       0              1
B        C       1              2
B        D       1              2
X        Y       0              2
X        D       0              2 
Y        Z       2              3
Run Code Online (Sandbox Code Playgroud)

This represents a tree that looks like this

       A  X
      /  / \
     B  /   \
    /\ /     \
   C  D       Y
              |
              Z
Run Code Online (Sandbox Code Playgroud)

I want to produce something that looks like this:

root    children
A       [B,C,D]
X       [D,Y,Z]
Run Code Online (Sandbox Code Playgroud)

or

root   child
A      B
A      C
A      D
X      D
X      Y
X      Z 
Run Code Online (Sandbox Code Playgroud)

What is the fastest way to do so without looping. I have a really large dataframe.

Dan*_*ejo 10

我建议您使用networkx,因为这是一个图形问题。特别是后代函数:

import networkx as nx
import pandas as pd

data = [['A', 'B', 0, 1],
        ['B', 'C', 1, 2],
        ['B', 'D', 1, 2],
        ['X', 'Y', 0, 2],
        ['X', 'D', 0, 2],
        ['Y', 'Z', 2, 3]]

df = pd.DataFrame(data=data, columns=['parent', 'child', 'parent_level', 'child_level'])

roots = df.parent[df.parent_level.eq(0)].unique()
dg = nx.from_pandas_edgelist(df, source='parent', target='child', create_using=nx.DiGraph)

result = pd.DataFrame(data=[[root, nx.descendants(dg, root)] for root in roots], columns=['root', 'children'])
print(result)
Run Code Online (Sandbox Code Playgroud)

输出量

  root   children
0    A  {D, B, C}
1    X  {Z, Y, D}
Run Code Online (Sandbox Code Playgroud)


piR*_*red 5

递归

def find_root(tree, child):
    if child in tree:
        return {p for x in tree[child] for p in find_root(tree, x)}
    else:
        return {child}

tree = {}
for parent, child in zip(df.parent, df.child):
    tree.setdefault(child, set()).add(parent)

descendents = {}
for child in tree:
    for parent in find_root(tree, child):
        descendents.setdefault(parent, set()).add(child)

pd.DataFrame(descendents.items(), columns=['root', 'children'])

  root   children
0    A  {B, D, C}
1    X  {Z, D, Y}
Run Code Online (Sandbox Code Playgroud)

您也可以设置find_root为发电机

def find_root(tree, child):
    if child in tree:
        for x in tree[child]:
            yield from find_root(tree, x)
    else:
        yield child
Run Code Online (Sandbox Code Playgroud)

此外,如果要避免递归深度问题,可以使用“迭代器堆栈”模式来定义find_root

def find_root(tree, child):
    stack = [iter([child])]
    while stack:
        for node in stack[-1]:
            if node in tree:
                stack.append(iter(tree[node]))
            else:
                yield node
            break
        else:  # yes!  that is an `else` clause on a for loop
            stack.pop()
Run Code Online (Sandbox Code Playgroud)