【问题标题】:How to create edges in a network conditionally (using python Networkx package) based on other edges between nodes?如何根据节点之间的其他边有条件地(使用python Networkx包)在网络中创建边?
【发布时间】:2019-11-24 00:07:36
【问题描述】:

我有一个数据集显示父子关系,但没有兄弟姐妹的子子关系。我正在使用 python 的 Networkx 包(python 版本 3.6)构建网络。我想在兄弟姐妹之间添加边(如果孩子共享父母,他们是兄弟姐妹)。我该怎么做?

我发现了一些关于条件边创建的问题,但在这些问题中,条件不依赖于其他节点属性(例如,某些节点的现有边):

python networkx remove nodes and edges with some condition

但我不确定如何在我的情况下制定条件,以实现我想要的。

import networkx as nx

dat = {'child':[1,1,4,4,5,5,8,8], 'parent':[2,3,2,3,6,7,6,7]} 

# Create DataFrame 
data = pd.DataFrame(dat) 

# Create graph with known connections
G = nx.Graph()

def create_edges(row):
    return G.add_edge(row['child'],row['parent'])

data.apply(create_edges, axis=1)

我想在节点 1 和 4 以及节点 5 和 8 之间创建边(因为它们共享父节点并且显然是兄弟姐妹),但不在 1 和 5 或 4 和 8 之间。

【问题讨论】:

  • 那么最终的网络应该只有子节点还是父节点?
  • 谢谢,亚图。我应该更清楚,对不起。回答你的问题:它应该有两个——节点不会改变,我只需要在兄弟姐妹之间添加边。

标签: python networkx graph-theory


【解决方案1】:

我希望我不会让事情变得过于复杂,但这就是我的做法:

首先,将孩子按共同父母分组。生成的变量parents_children 是一个dict,其中父母作为键,每个父母的孩子的集合作为值。

parents_children = {parent: {child for child in dat['child'] 
                         if (parent,child) in list(zip(dat['parent'],dat['child']))} 
                for parent in dat['parent']}

然后,遍历具有相同父母的一对孩子,并在他们之间添加一条边:

from itertools import combinations
for children in parents_children.values():
    for children_couple in combinations(children,2):
        G.add_edge(*children_couple)

我自己运行它,我认为它得到了正确的结果。

【讨论】:

  • 谢谢你,伊塔马尔。这正是我所需要的。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2017-12-22
  • 2023-02-23
  • 2016-07-04
  • 1970-01-01
  • 2019-03-12
  • 2023-04-02
  • 1970-01-01
  • 2019-06-14
相关资源
最近更新 更多