代码之家  ›  专栏  ›  技术社区  ›  ellen

当一个属性相同时连接图中的节点(networkx)

  •  1
  • ellen  · 技术社区  · 6 年前

    我想创建一个图表,如果一个特定属性相同,它会自动在节点之间添加边。图中的节点表示学生。我正在向节点添加两个属性: university_id full_name . 我只想在两个人上同一所大学的时候,在他们之间增加一个优势。

    我一直在研究这个解决方案: NetworkX: add edges to graph from node attributes

    通过测试,这个解决方案似乎连接了一个图的所有边缘,不管任何属性是否相同。有没有一个简单的解决方案,我只能根据学生的 大学学报 ?

    这是我的代码:

    import matplotlib.pyplot as plt
    import networkx as nx
    import MySQLdb
    
    # #############################################################################
    # Retrieve the data from remote server.
    myDB = MySQLdb.connect(host="*,port=3306,user="mysql",passwd="***")
    cHandler = myDB.cursor()
    cHandler.execute("USE research_project")
    cHandler.execute("SELECT * FROM students")
    results = cHandler.fetchall()
    
    G = nx.Graph()
    for items in results:
            # items[0] is a unique ID, items[1] = university_id, items[2] = full name
            G.add_node(items[0], attr_dict={'university_id': items[1], 'full_name': items[2]})
    
    for node_r, attributes in G.nodes(data=True):
        key_set = set(attributes.keys())
        G.add_edges_from([(node_r, node) for node, attributes in G.nodes(data=True)
                          if key_set.intersection(set(attributes.keys()))
                          and node != node_r])
    
    nx.draw(G)
    plt.show()
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   ellen    6 年前
    from __future__ import print_function
    import matplotlib.pyplot as plt
    import networkx as nx
    import MySQLdb
    
    
    # #############################################################################
    # Retrieve the data from remote server.
    myDB = MySQLdb.connect(host="*,port=3306,user="mysql",passwd="***")
    cHandler = myDB.cursor()
    cHandler.execute("USE research_project")
    cHandler.execute("SELECT * FROM students")
    results = cHandler.fetchall()
    
    G = nx.Graph()
    for items in results:
        G.add_node(items[0], attr_dict={'university_id': items[1], 'full_name': items[2]})
    
    for node_r in G.nodes(data=True):
        for node in G.nodes(data=True):
            if node != node_r and node[1]['attr_dict']['university_id'] == node_r[1]['attr_dict']['university_id']:
                G.add_edge(node[0], node_r[0], attr_dict=None)
    
    nx.draw(G, with_labels=True)
    plt.show()
    

    我在一些小的数据集上测试了上面的内容,它似乎可以工作。 我有种预感,发生的事情与我向节点添加属性的方式有关。

    上述解决方案的警告是,它在运行时速度非常慢。只要我能想出一个更快的解决方案,我就会更新我的答案。