首页 > 解决方案 > python networkx允许重复节点

问题描述

我正在尝试查看 3 列并创建一个迭代树列表。

在此处输入图像描述

我想迭代到顶部,直到找到空父代码并显示完整的树视图。

我正在使用的代码:

df = df.fillna('null')
G = nx.DiGraph()
G.add_edges_from(zip(df['ChildCode'],df['parentCode'] ))
G = nx.relabel_nodes(G, mapping=df.set_index('ChildCode')['ChildOrg'].to_dict())    

我对节点的重新标记是删除重复值,即财务,因此结果有点偏离。如果有办法在重新标记时允许重复节点?

由于某种原因,我得到的结果无法识别重复的 childorg 条目并将所有条目分配给相同的父代码。

在此处输入图像描述

我期待如下结果:

在此处输入图像描述

标签: pythonnetworkx

解决方案


If df['null'] contains numbers, then they are not subscriptable. For example, 123456[1:3] would raise the same error. I guess you want the following code:

df['Path'] = df['null'].apply(lambda x: '/'.join(str(x)[-2::-1]))

Another potential problem is filling out the missing values by 'null'. Do you want 'un' to be returned in this case? If not, please treat these values separately. For example,

df['Path'] = df['null'].apply(lambda x: '/'.join(str(x)[-2::-1]) if x != 'null' else 'null')

推荐阅读