来自数据库的加权边列表的图形

时间:2013-04-16 09:08:10

标签: python networkx

我有存储在数据库中的加权边列表。 如何从中轻松创建图表(无需将其写入文件并阅读)

这里可再现

import sqlite3 
con = sqlite3.connect(":memory:")

with con:
    cur = con.cursor()    
    cur.execute("CREATE TABLE DATEN(Source TEXT, Target TEXT, Weight REAL)")
    cur.execute("INSERT INTO DATEN VALUES('X33', 'X20', 0.014)") 
    cur.execute("INSERT INTO DATEN VALUES('X32', 'X20', 0.024)") 
    cur.execute("INSERT INTO DATEN VALUES('X23', 'X20', 0.167)") 
    cur.execute("INSERT INTO DATEN VALUES('X23', 'X32', 0.015)") 
    cur.execute("INSERT INTO DATEN VALUES('X32', 'X33', 0.003)") 
    cur.execute("INSERT INTO DATEN VALUES('X23', 'X33', 0.035)")


cur.execute('SELECT * FROM DATEN')
data = cur.fetchall()

我创建图表的尝试失败了:

import networkx as nx
G = nx.Graph()
for x in data:
     x1 = {'source': data[0][0], 'target': data[0][1], 'weight':  data[0][2]} 
     print x1 

     G.add_edge(x1)  # THIS IS NOT WORKING 

有更简单的方法吗?

4 个答案:

答案 0 :(得分:5)

游标是一个迭代器,它在执行SELECT语句后产生行。例如,不是使用

将所有结果提取到列表中
rows = cur.fetchall()

您可以使用

迭代行
for row in cur:

但是,由于NetworkX add_weighted_edges_from方法接受迭代器,您可以直接传递cur

G.add_weighted_edges_from(cur)

这是多态性的一个很好的例子。 NetworkX的设计者不需要做任何特殊的事情,甚至可以预期sqlite3游标可以作为参数传递,他们只需要编写代码,假设第一个参数是迭代器。


import networkx as nx
import sqlite3 
import matplotlib.pyplot as plt

with sqlite3.connect(":memory:") as con:
    cur = con.cursor()    
    cur.execute("CREATE TABLE DATEN(Source TEXT, Target TEXT, Weight REAL)")
    cur.execute("INSERT INTO DATEN VALUES('X33', 'X20', 0.014)") 
    cur.execute("INSERT INTO DATEN VALUES('X32', 'X20', 0.024)") 
    cur.execute("INSERT INTO DATEN VALUES('X23', 'X20', 0.167)") 
    cur.execute("INSERT INTO DATEN VALUES('X23', 'X32', 0.015)") 
    cur.execute("INSERT INTO DATEN VALUES('X32', 'X33', 0.003)") 
    cur.execute("INSERT INTO DATEN VALUES('X23', 'X33', 0.035)")

    G = nx.Graph()
    cur.execute('SELECT Source, Target, Weight FROM DATEN')
    G.add_weighted_edges_from(cur)    

nx.draw(G)
plt.show()

enter image description here

答案 1 :(得分:0)

Graph.add_edge()不会将dict作为参数,它至少需要两个节点和可选的关键字参数。试试这个:

import networkx as nx
G = nx.Graph()
for x in data:
     G.add_edge(x[0], x[1], weight=x[2])

答案 2 :(得分:0)

首先,你能给我们提供错误信息吗?

然后,您似乎无法正确使用add_edge(请参阅:http://networkx.github.io/documentation/latest/reference/generated/networkx.Graph.add_edge.html#networkx.Graph.add_edge

你应该尝试添加这样的边缘:

import networkx as nx
G = nx.Graph()
for x in data:
    G.add_edge(x[0], x[1], weight=x[2])

答案 3 :(得分:0)

这有效

f=open('G_train.txt','r')
data=f.read()
EDGES=ast.literal_eval(data)

g = nx.DiGraph((x, y, {'weights': v}) for (x, y), v in Counter(EDGES).items())

print("Edges", g.edges(data=True), sep='\n')