python - 寻找终极父母
问题描述
我正在尝试用 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。
解决方案
用于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
推荐阅读
- ios - 如何在我的控制器中快速添加过渡动画?
- android - 进度条 setProgress 在 UI 线程上不起作用
- javascript - 在材料表单元格角度切换此元素
- java - 无法使用带有 Apache 2.4 FOP 的 Spring boot 2.1.6.RELEASE 编译应用程序
- android - 如何删除约束布局中视图之间的额外空间?
- android - Android 应用程序仅在某些设备中崩溃,其中大部分是华为
- r - 如何获取未选择的行号?
- enterprise - 在 Enterprise Architect 上创建 AOM 目标模型
- sass - Gulp 错误:未找到:通知发送(Ubuntu)
- c# - 在我的表中,第一行是空白的,最后一行在 ASPX 页面中丢失