首页 > 解决方案 > 寻找终极父母

问题描述

我正在尝试用 Dir pandas 找到最终的父母。但是该任务有一个特点,即图表并不真正适合,或者我根本不知道如何正确使用它。输入:

孩子 家长 班级
1001 8888 一个
1001 1002 D
1001 1002 C
1001 1003 C
1003 6666 G
1002 9999 H

输出:

孩子 Ultimate_Parent 班级 联系
1001 8888 一个 直接的
1001 9999 D 间接
1001 9999 C 间接
1001 6666 C 间接
1003 6666 G 直接的
1002 9999 H 直接的

我愿意:

import pandas as pd 
import networx as nx 
df = pd.DataFrame({'Child': ['1001', '1001', '1001', '1001', '1003', '1004'], 'Parent': ['8888', '1002', '1002', '1003', '6666', '9999'],'Class': ['A','D','C','C','G','H']})
    def get_hierarchy (df):
        DiG=nx.from_pandas_adgelist (df,'child','parent',create_using=nx.DiGraph())
        return pd.DataFrame.from_records([(n1,n2) for n1 in DiG.nodes() for n2 in nx.ancestors(DiG, n1)], columns=['child','Ultimate_parent'])
    df=df.toPandas()
    df=get_hierarchy(df)
    return df

而且我无法在此处了解如何使用 Class 属性,以 D 和 C 类显示两次 1001。

标签: pythonpandaspysparkhierarchy

解决方案


用于G.predecessors检测当前Parent是否是树的根。如果是,则连接是,Direct否则连接是Indirect

G = nx.from_pandas_edgelist(df, source='Parent', target='Child',
                            create_using=nx.DiGraph)

roots = [node for node, degree in G.in_degree() if degree == 0]

ultimate_parent = [node if node in roots else list(G.predecessors(node))[0] 
                       for node in df['Parent']]

df['Ultimate_Parent'] = ultimate_parent
df['Connection'] = np.where(df['Parent'] == df['Ultimate_Parent'],
                            'Direct', 'Indirect')

输出:

>>> df
   Child  Parent Class  Ultimate_Parent Connection
0   1001    8888     A             8888     Direct
1   1001    1002     D             9999   Indirect
2   1001    1002     C             9999   Indirect
3   1001    1003     C             6666   Indirect
4   1003    6666     G             6666     Direct
5   1002    9999     H             9999     Direct

推荐阅读