识别树中的根父母及其所有孩子 [英] Identifying root parents and all their children in trees

查看:57
本文介绍了识别树中的根父母及其所有孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫数据框:

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

这代表一棵看起来像这样的树

This represents a tree that looks like this

       A  X
      /  / \
     B  /   \
    /\ /     \
   C  D       Y
              |
              Z

我想制作看起来像这样的东西:

I want to produce something that looks like this:

root    children
A       [B,C,D]
X       [D,Y,Z]

root   child
A      B
A      C
A      D
X      D
X      Y
X      Z 

没有循环的最快方法是什么.我有一个非常大的数据框.

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

推荐答案

我建议你使用 networkx,因为这是一个图形问题.特别是 descendants 函数:

I suggest you use networkx, as this is a graph problem. In particular the descendants function:

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)

输出

  root   children
0    A  {D, B, C}
1    X  {Z, Y, D}

这篇关于识别树中的根父母及其所有孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆