[英]How to convert a bipartite list of edges into a graph in NetworkX with each set of nodes having overlapping labels?
I'm currently trying to convert a JSON file I have into a bipartite graph using NetworkX.我目前正在尝试使用 NetworkX 将我拥有的 JSON 文件转换为二部图。 My data looks like this:
我的数据如下所示:
'edges': [
{'A': 8, 'B': 6},
{'A': 21, 'B': 4},
{'A': 27, 'B': 6},
{'A': 4, 'B': 5},
...
]
Basically, I have two sets of nodes: A and B. The list of edges than describes how a node of set A connects with a node of set B.基本上,我有两组节点:A 和 B。边列表描述了集合 A 的节点如何与集合 B 的节点连接。
My issue is that the nodes have overlapping identifiers.我的问题是节点具有重叠的标识符。 In other words, I have nodes 0, 1, 2, etc. in set A, and 0, 1, 2, etc. in B (not necessarily the same number of nodes, but their values overlap).
换句话说,我在集合 A 中有节点 0、1、2 等,在 B 中有 0、1、2 等(节点数不一定相同,但它们的值重叠)。 When I try to add all the nodes into my graph, I don't get all of the nodes, since some are repeated.
当我尝试将所有节点添加到我的图中时,我没有得到所有节点,因为有些节点是重复的。
How can I deal with having repeat nodes in my two sets?我如何处理在我的两个集合中有重复节点? They are actually different nodes, but NetworkX isn't treating them as such.
它们实际上是不同的节点,但 NetworkX 并没有这样对待它们。 I saw that you can set a "value" to a node, but I'm not sure how to fit everything together.
我看到您可以为节点设置“值”,但我不确定如何将所有内容组合在一起。
In the end, I would like to have a way to generate the nodes such that I can add edges to my graph in the following way:最后,我想有一种方法来生成节点,以便我可以通过以下方式将边添加到我的图中:
import networkx as nx
G = nx.Graph()
# Add nodes here
# Add edges
G.add_edges_from(
(edge['B'], edge['A'])
for edge in graph['edges']
)
You can add nodes to graph with ID's equal not to values in your dicts, but equal to AB-type plus values:您可以将节点添加到图形中,其 ID 不等于您的字典中的值,但等于 AB 类型加值:
import networkx as nx
# Create edges dict and graph
edges = [
{'A': 8, 'B': 6},
{'A': 21, 'B': 4},
{'A': 27, 'B': 6},
{'A': 4, 'B': 5},
]
G = nx.Graph()
for edge in edges:
# Create A-id
a_id = 'A' + str(edge['A'])
# Add node with A-id to graph
G.add_node(a_id)
# Add value to node data
G.nodes[a_id]['value'] = edge['A']
# Create B-id
b_id = 'B' + str(edge['B'])
# Add node with B-id to graph
G.add_node(b_id)
# Add value to node data
G.nodes[b_id]['value'] = edge['B']
# Add A-id - B-id edge to graph
G.add_edge(a_id, b_id)
If you will draw the graph:如果你要绘制图形:
nx.draw(
G,
node_color='#FF0000',
with_labels=True
)
You will get something like this:你会得到这样的东西:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.