簡體   English   中英

當一個屬性相同時連接圖中的節點(NetworkX)

[英]Connect nodes in a graph when one attribute is the same (NetworkX)

我想創建一個圖,如果一個特定的屬性相同,該圖將自動在節點之間添加邊。 我圖中的節點代表學生。 我向節點添加了兩個屬性: university_idfull_name 我只想在兩個人上同一所大學時在他們之間增加優勢。

我一直在研究此解決方案: NetworkX:從節點屬性向圖形添加邊

通過測試,似乎此解決方案將圖形的所有邊連接起來,而無論任何屬性是否相同。 有沒有一種簡單的解決方案可以僅根據學生的university_id來聯系學生?

這是我的代碼:

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()
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()

我在少量數據上測試了上面的方法,它似乎可以工作。 我有一種預感,發生的事情與我向節點添加屬性的方式有關。

上述解決方案的警告是,運行時異常緩慢。 只要有更快的解決方案,我都會更新答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM