python 工具包 networkx 使用方法

Published in categories blog  Technology  tagged with #networkx  #python 
import networkx as nx
print nx
<module 'networkx' from '/usr/local/lib/python2.7/dist-packages/networkx/__init__.pyc'>

创建图

import networkx as nx

g = nx.Graph() g.add_node(1) g.add_edge(2,3) g.add_edge(3,2) #for nodircted graph, they are the same edge. g.add_edge(1,2) print g.nodes() print g.edges() print g.number_of_edges()

#directed network g1 = nx.DiGraph() #weighted networks g1.add_weighted_edges_from([(1,2,1.5)])#u,v,w are parameters for src, dest and weight print g1.get_edge_data(1,2)

图算法

#algathm

path = nx.all_pairs_shortest_path(g)

print path[1][3]
[1, 2, 3]

绘制图

import networkx as nx
%matplotlib inline

g = nx.Graph()
edge_list = [(1,2),(1,3),(1,4),(2,3),(2,4),(2,5),(3,4),(3,5),(4,6)]
g.add_edges_from(edge_list)

nx.draw(g, node_color='y', with_labels=True, node_size=800)  

png

利用networkX分析图的k-shell和k-core

k_shell(G,k=n)得到的是由所有k-shell值为n节点组成的G的子图

k_core(G,k=n)得到的是由所有k-shell值不小于n的节点组成的G的子图

ks = nx.k_shell(g,1)
print ks.nodes()

kc = nx.k_core(g,2)
nx.draw(kc, node_color='y', with_labels=True, node_size=800)
[6]

png

从 neo4j 导入数据


References:

  1. [NetworkX使用笔记:读入外部文件并转换成各种格式   Spark & Shine](http://sparkandshine.net/networkx-use-notes-read-external-file-convert-to-other-formats/)
comments powered by Disqus