简体   繁体   English

如何将 JSON 文件转换为 Python 中带有 library.networkx 的图形?

[英]How to convert a JSON file to a graph with library networkx in Python?

I have a big JSON file and I want to convert it with.networkx library to a graph.我有一个很大的 JSON 文件,我想用 .networkx 库将它转换为图形。 The JSON file contains so many nodes like: JSON 文件包含很多节点,例如:

{"data": [{ "d": 2, "source": "C", "target": "L" },...]} {“数据”:[{“d”:2,“来源”:“C”,“目标”:“L”},...]}

I already opened the JSON file and I extracted each "data" dictionary inside the JSON file.我已经打开了 JSON 文件,并提取了 JSON 文件中的每个“数据”字典。 However, I do not know how to use.networkx to convert all of my source, target nodes with considering the attribute "d" to a graph.但是,我不知道如何使用 .networkx 将我所有的源节点、目标节点考虑到属性“d”转换为图形。

import networkx as nx
import json

lst = list()
with open('json_file.json') as json_load:
    data = json.load(json_load)
    lst.extend( data["edges"])  
    d, src, tgt = [],[], [], [] 
    
    for elem in lst:
      d.append(elem["data"]["d"])
      src.append(elem["data"]["source"])
      tgt.append(elem["data"]["target"])

G = nx.Graph()      
G.add_edges_from([tuple(zip(src, tgt))])

When I wrote the last line for inserting the edges into the G graph, it did not really work.当我写最后一行将边插入 G 图中时,它并没有真正起作用。 I had an error.我有一个错误。 I guess because I did not properly merge the source and target nodes together.我猜是因为我没有正确地将源节点和目标节点合并在一起。

Also, I have another problem as well.另外,我还有另一个问题。 I couldn't figure out how to consider attribute "d" for each node in the graph as well.我也不知道如何为图中的每个节点考虑属性“d”。

The argument passed to G.add_edges_from is not valid, specifically the result of zip -ping several iterables together is already an iterable of tuples, so only zip(src, tgt, d) is needed.传递给G.add_edges_from的参数无效,特别是zip的结果 - ping 几个可迭代对象已经是一个可迭代的元组,因此只需要zip(src, tgt, d) Next, make sure that d is a list of dictionaries, as per function requirements.接下来,根据 function 的要求,确保d是字典列表。

Here's a reproducible example:这是一个可重现的例子:

import networkx as nx

src = ["A", "B", "C"]
tgt = ["B", "C", "D"]
d = [{"weight": 2}, {"weight": 3}, {"weight": 4}]

G = nx.Graph()
G.add_edges_from(zip(src, tgt, d))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM