如何根据节点之间的其他边有条件地(使用 python Networkx 包)在网络中创建边?
How to create edges in a network conditionally (using python Networkx package) based on other edges between nodes?
我有一个显示 parent-child 关系但没有 child-child 兄弟姐妹关系的数据集。我正在使用 python 的 Networkx 包(python 版本 3.6)构建网络。我想在兄弟姐妹之间添加边缘(如果 children 共享 parents,他们是兄弟姐妹)。我该怎么做?
我发现了一些关于条件边创建的问题,但在这些问题中,条件不依赖于其他节点属性(例如,某些节点的现有边):
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 之间创建边(因为它们共享 parents 并且显然是兄弟姐妹)但不在 1 和 5 或 4 和 8 之间。
我希望我没有把事情复杂化,但这就是我要走的路:
首先,将 children 按联合 parent 分组。结果变量 parents_children
是一个 dict
,以 parents 作为键,每个 parent 的集合 children 作为值。
parents_children = {parent: {child for child in dat['child']
if (parent,child) in list(zip(dat['parent'],dat['child']))}
for parent in dat['parent']}
然后,遍历具有相同 parent 的 children 对,并在它们之间添加一条边:
from itertools import combinations
for children in parents_children.values():
for children_couple in combinations(children,2):
G.add_edge(*children_couple)
我运行它在我这边,我认为它得到了正确的结果。
我有一个显示 parent-child 关系但没有 child-child 兄弟姐妹关系的数据集。我正在使用 python 的 Networkx 包(python 版本 3.6)构建网络。我想在兄弟姐妹之间添加边缘(如果 children 共享 parents,他们是兄弟姐妹)。我该怎么做?
我发现了一些关于条件边创建的问题,但在这些问题中,条件不依赖于其他节点属性(例如,某些节点的现有边):
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 之间创建边(因为它们共享 parents 并且显然是兄弟姐妹)但不在 1 和 5 或 4 和 8 之间。
我希望我没有把事情复杂化,但这就是我要走的路:
首先,将 children 按联合 parent 分组。结果变量 parents_children
是一个 dict
,以 parents 作为键,每个 parent 的集合 children 作为值。
parents_children = {parent: {child for child in dat['child']
if (parent,child) in list(zip(dat['parent'],dat['child']))}
for parent in dat['parent']}
然后,遍历具有相同 parent 的 children 对,并在它们之间添加一条边:
from itertools import combinations
for children in parents_children.values():
for children_couple in combinations(children,2):
G.add_edge(*children_couple)
我运行它在我这边,我认为它得到了正确的结果。