查找最终的父代 [英] Finding ultimate parent

查看:15
本文介绍了查找最终的父代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力寻找有Dir pandas 的终极父母。但这项任务有一个特长,那就是图表不太适合,或者我只是不知道如何正确使用它。 输入:

子项 父级
1001 8888 A
1001 1002 D
1001 1002 C
1001 1003 C
1003 6666 G
1002 9999 H

输出:

子项 旗舰_父级 连接
1001 8888 A 直接
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。

推荐答案

使用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

这篇关于查找最终的父代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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