![](/img/trans.png)
[英]how to find clusters with a network based on density and weight of edges in python - networkx package
[英]How to create edges in a network conditionally (using python Networkx package) based on other edges between nodes?
我有一个数据集显示父子关系,但没有兄弟姐妹的子子关系。 我正在使用 python 的 Networkx 包(python 3.6 版)构建网络。 我想在兄弟姐妹之间添加边缘(如果孩子共享父母,他们是兄弟姐妹)。 我怎样才能做到这一点?
我发现了一些关于条件边创建的问题,但在这些问题中,条件不依赖于其他节点属性(例如,某些节点的现有边):
但我不确定如何在我的情况下制定条件,以实现我想要的。
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 之间。
我希望我不会让事情过于复杂,但这就是我的做法:
首先,由共同父母将孩子分组。 结果变量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)
我在我身边运行它,我认为它得到了正确的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.