有没有办法在 NetworkX 中找到节点之间的双向关系?
Is there a way to find a bidirectional relationship between nodes in NetworkX?
我有一个 Twitter 用户及其关注者网络,我正在使用 NetworkX 对其进行建模。我正在尝试在用户之间找到双向 link,即如果一个节点跟随其邻居之一,那么该邻居是否也跟随该节点。
NetworkX 中是否有内置函数可以完成此任务?我尝试使用 nx.reciprocity()
但它只是 returns 单个值而不是字典。
可以用networkx.Graph.has_edge
判断两个节点之间是否存在边连接。然后,这可用于测试节点之间是否存在相反方向的边缘。
import networkx as nx
def have_bidirectional_relationship(G, node1, node2):
return G.has_edge(node1, node2) and G.has_edge(node2, node1)
G = nx.DiGraph()
G.add_edge(1, 2)
G.add_edge(2, 1)
G.add_edge(3, 4)
print(f"Nodes 1, 2 have opposite edges: {have_bidirectional_relationship(G, 1, 2)}")
print(f"Nodes 3, 4 have opposite edges: {have_bidirectional_relationship(G, 3, 4)}")
输出
Nodes 1, 2 have opposite edges: True
Nodes 3, 4 have opposite edges: False
查找具有双向关系的所有节点
biconnections = set()
for u, v in G.edges():
if u > v: # Avoid duplicates, such as (1, 2) and (2, 1)
v, u = u, v
if have_bidirectional_relationship(G, u, v):
biconnections.add((u, v))
print(biconnections)
输出
{(1, 2)}
我有一个 Twitter 用户及其关注者网络,我正在使用 NetworkX 对其进行建模。我正在尝试在用户之间找到双向 link,即如果一个节点跟随其邻居之一,那么该邻居是否也跟随该节点。
NetworkX 中是否有内置函数可以完成此任务?我尝试使用 nx.reciprocity()
但它只是 returns 单个值而不是字典。
可以用networkx.Graph.has_edge
判断两个节点之间是否存在边连接。然后,这可用于测试节点之间是否存在相反方向的边缘。
import networkx as nx
def have_bidirectional_relationship(G, node1, node2):
return G.has_edge(node1, node2) and G.has_edge(node2, node1)
G = nx.DiGraph()
G.add_edge(1, 2)
G.add_edge(2, 1)
G.add_edge(3, 4)
print(f"Nodes 1, 2 have opposite edges: {have_bidirectional_relationship(G, 1, 2)}")
print(f"Nodes 3, 4 have opposite edges: {have_bidirectional_relationship(G, 3, 4)}")
输出
Nodes 1, 2 have opposite edges: True
Nodes 3, 4 have opposite edges: False
查找具有双向关系的所有节点
biconnections = set()
for u, v in G.edges():
if u > v: # Avoid duplicates, such as (1, 2) and (2, 1)
v, u = u, v
if have_bidirectional_relationship(G, u, v):
biconnections.add((u, v))
print(biconnections)
输出
{(1, 2)}