在一棵有Pandas的树上找到所有叶子节点的祖先

2024-04-20 14:39:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个表,有两列,'parent'和'child'。这是从SAP(ERP)下载的SETNODE table。需要在python中创建一个dataframe,它将每个级别作为相对于其父级和之前所有级别的列。在

在python3+中。在

整个关系的级别数未知(或总是在变化),因此无法始终定义最大级别。我想创建一个完整的数据帧表,显示所有级别的所有父/子关系。现在大概有15个级别,但如果使用其他数据,可能会上升到20个或更多。在

例如(example_df)这两列:

enter image description here

example_df = pd.DataFrame({'parent:['a','a','b','c','c','f'],'child':['b','c','d','f','g','h']})

要给出输出数据帧(解决方案示例):

enter image description here

^{pr2}$

Tags: 数据childdataframedferp定义关系example
1条回答
网友
1楼 · 发布于 2024-04-20 14:39:19

这可以使用networkx库来解决。首先,从数据帧构建一个有向图,然后找到叶节点的所有祖先。在

import networkx as nx

leaves = set(df.child).difference(df.parent)
g = nx.from_pandas_edgelist(df, 'parent', 'child', create_using=nx.DiGraph())
ancestors = {
    n: nx.algorithms.dag.ancestors(g, n) for n in leaves
}

(pd.DataFrame.from_dict(ancestors, orient='index')
   .rename(lambda x: 'parent_{}'.format(x+1), axis=1)
   .rename_axis('child')
   .fillna(''))

      parent_1 parent_2 parent_3
child                           
h            a        c        f
g            a        c         
d            a        b         

相关问题 更多 >