[python] networkx的使用
2018-10-31 本文已影响0人
VanJordan
个人认为最好的创建图的方式就是通过给Graph加edgelist的方式来创建图
edgelist = [('as',4,{'weight':223}),(4,'sadf',{"hei":2342})]
H = nx.Graph(edgelist)
print(list(H.nodes))
print(H[4])
print(H['as'][4])
>>['as', 4, 'sadf']
{'as': {'weight': 223}, 'sadf': {'hei': 2342}}
{'weight': 223}
给边绑定属性
>>> G.add_edge(1, 3)
>>> G[1][3]['color'] = "blue"
>>> G.edges[1, 2]['color'] = "red"
给边加默认属性
>>> G.add_edge(1, 2, weight=4.7 )
>>> G.add_edges_from([(3, 4), (4, 5)], color='red')
>>> G.add_edges_from([(1, 2, {'color': 'blue'}), (2, 3, {'weight': 8})])
>>> G[1][2]['weight'] = 4.7
>>> G.edges[3, 4]['weight'] = 4.2
给结点绑定属性
>>> G.add_node(1, time='5pm')
>>> G.add_nodes_from([3], time='2pm')
>>> G.nodes[1]
{'time': '5pm'}
>>> G.nodes[1]['room'] = 714
>>> G.nodes.data()
NodeDataView({1: {'room': 714, 'time': '5pm'}, 3: {'time': '2pm'}})
根据某一个属性遍历所有的边。
>>> for (u, v, wt) in FG.edges.data('weight'):
... if wt < 0.5: print('(%d, %d, %.3f)' % (u, v, wt))
(1, 2, 0.125)
(3, 4, 0.375)
调用图算法
path=nx.all_pairs_shortest_path(G) #调用多源最短路径算法,计算图G所有节点间的最短路径
print(path[0][2]) #输出节点0、2之间的最短路径序列: [0, 1, 2]
存储图和加载图
nx.write_gpickle(H, "D:\\code\\Hgraph.gpickle")
T = nx.read_gpickle("D:\\code\\Hgraph.gpickle")
有向图的使用
DG = nx.DiGraph([('a','b',{'relation':'IsA'}),('a','c',{'relation':'RelatedTo'}),('d','a',{'relation':'RelatedTo'})])
print(list(DG['a']))
print(DG['a']['b']['relation'])