NetworkX包
NetworkX是一个创建,操作,研究复杂网络的结构,动态,功能的python包。
#创建一个network
import networkx as nx
G = nx.Graph()
#nodes
import networkx as nx
G = nx.Graph()
'''
在networkx中,nodes可以是任何能够hash的对象,
例如a text string,an image,an XML object,another Graph,a customized node object等等''' G.add_node(11)
G.add_nodes_from([12, 13])
print(G.nodes()) H = nx.path_graph(10)
G.add_nodes_from(H)
G.add_node(H)
print(G.nodes()) '''
输出:
[11, 12, 13]
[11, 12, 13, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, <networkx.classes.graph.Graph object at 0x00000000021C8828>] G可以将H中的node作为自己的node,也可以将H单独作为一个node'''
添加edges
import networkx as nx
G = nx.Graph() '''G.add_edge(1, 2)
e = (2, 3)
G.add_edge(*e)
G.add_edges_from([(4, 5), (6, 7)])''' '''
adding any ebunch of edges. An ebunch is any iterable container of edge-tuples.
An edge-tuple can be a 2-tuple of nodes or a 3-tuple with
2 nodes followed by an edge attribute dictionary, e.g., (2, 3, {'weight': 3.1415})'''
H = nx.path_graph(10)
G.add_edges_from(H.edges()) print(G.nodes())
print(G.edges())
print(G.number_of_edges())
print(G.number_of_nodes())
'''
输出:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
9
10
'''
print('..............')
print(list(G.adj[1]))
print(G.neighbors(1))
print(G.degree(1))
'''
输出:
[0, 2]
[0, 2]
2
''' print(G.edges([2, 5]))
print(G.degree([2, 3]))
'''
输出:
[(2, 1), (2, 3), (5, 4), (5, 6)]
{2: 2, 3: 2}
''' G.remove_node(2)
G.remove_edge(6, 7) print(G.nodes())
print(G.edges())
'''
输出:
[0, 1, 3, 4, 5, 6, 7, 8, 9]
[(0, 1), (3, 4), (4, 5), (5, 6), (7, 8), (8, 9)]
''' G.add_edge(6, 7)
H = nx.DiGraph(G)
print(H.edges())
'''
[(0, 1), (1, 0), (3, 4), (4, 3), (4, 5), (5, 4), (5, 6), (6, 5), (6, 7), (7, 8), (7, 6), (8, 7), (8, 9), (9, 8)]
''' edgelist = [(0, 1), (2, 3), (4, 5)]
H = nx.Graph(edgelist)
print(H.edges())
'''
[(0, 1), (2, 3), (4, 5)]
'''
访问edges或neighbors:
#访问edges或neighbors
import networkx as nx
G = nx.Graph() H = nx.path_graph(7)
G.add_edges_from(H.edges()) print('G.nodes()为:', G.nodes())
print('G.edges()为:', G.edges())
'''
G.nodes()为: [0, 1, 2, 3, 4, 5, 6]
G.edges()为: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
''' print('...............')
print('G[1]为:', G[1])
print('G[1][2]为:', G[1][2])
'''
G[1]为: {0: {}, 2: {}}
G[1][2]为: {}
''' G.add_edge(1, 3)
G[1][3]['color'] = 'blue'
G[1][3]['size'] = 22 print('...............')
print('G[1]为:', G[1])
print('G[1][3]为:', G[1][3])
'''
G[1]为: {0: {}, 2: {}, 3: {'color': 'blue', 'size': 22}}
G[1][3]为: {'color': 'blue', 'size': 22}''' print('...................')
print('G.adj.items()为: ', G.adj.items())
print('G.adjacency_list()为: ',G.adjacency_list())
print('G.adjlist_dict_factory为: ', G.adjlist_dict_factory)
'''
G.adj.items()为: dict_items([(0, {1: {}}), (1, {0: {}, 2: {}, 3: {'color': 'blue', 'size': 22}}), (2, {1: {}, 3: {}}), (3, {2: {}, 4: {}, 1: {'color': 'blue', 'size': 22}}), (4, {3: {}, 5: {}}), (5, {4: {}, 6: {}}), (6, {5: {}})])
G.adjacency_list()为: [[1], [0, 2, 3], [1, 3], [2, 4, 1], [3, 5], [4, 6], [5]]
G.adjlist_dict_factory为: <class 'dict'>
''' print('..........................')
FG = nx.Graph()
FG.add_weighted_edges_from([(1, 2, 0.125), (1, 3, 0.75), (2, 4, 1.2), (3, 4, 0.375)])
for n,nbrs in FG.adj.items():
for nbr, edgeAttr in nbrs.items():
wt = edgeAttr['weight']
if wt < 0.5:
print('(%d, %d, %.3f)' % (n, nbr, wt))
'''
(1, 2, 0.125)
(2, 1, 0.125)
(3, 4, 0.375)
(4, 3, 0.375)
'''
为graphs,nodes,edges添加属性
#Adding attributes to graphs, nodes, and edges
#任何python object比如weights,labels,colors都可以作为graphs,nodes,edges的属性 '''Graph attributes'''
import networkx as nx
G = nx.Graph(day='Friday')
print(G.graph)
#{'day': 'Friday'} #modify attributes
G.graph['day'] = "monday"
print(G.graph)
#{'day': 'monday'} '''Node attributes'''
#用add_node(),add_nodes_from()或G.nodes为node添加属性
G.add_node(1, time='11am')
G.add_nodes_from([3],time='2pm') print(G.node[1])
#{'time': '11am'}
G.node[1]['room'] = 714
print(G.node)
#{1: {'time': '11am', 'room': 714}, 3: {'time': '2pm'}} '''Edge Attributes'''
#用add_edge(), add_edges_from(),或下标来为edge添加或修改属性
G.add_edge(1, 2, weight=4.5)
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'] = 7878
G.edge[1][2]['color'] = 'wetuweywiu'
print(G.edge)
'''
{1: {2: {'weight': 7878, 'color': 'wetuweywiu'}}, 3: {4: {'color': 'red'}, 2: {'weight': 8}}, 2: {1: {'weight': 7878, 'color': 'wetuweywiu'}, 3: {'weight': 8}},
4: {3: {'color': 'red'}, 5: {'color': 'red'}}, 5: {4: {'color': 'red'}}}
'''
print(G.edges())
#[(1, 2), (3, 4), (3, 2), (4, 5)] print(G[1])#1的邻接node以及edge的属性
# {2: {'weight': 7878, 'color': 'wetuweywiu'}}
print(G[1][2])
#{'weight': 7878, 'color': 'wetuweywiu'}
print(G.edge[1][2])
#{'weight': 7878, 'color': 'wetuweywiu'} '''
总结:
访问node的具体属性,必须是G.node[u][attr], 而访问edge的具体属性可以是G.edge[u][v][attr]或G[u][v][attr]
G.node[u]:node u的所有属性, G.edge[u][v]或G[u][v]:边(u, v)的所有属性
G.node:所有点以及属性, G.edge:所有edge以及属性
'''
有向图:
import networkx as nx
DG = nx.DiGraph()
DG.add_weighted_edges_from([(1, 2, 0.5), (3, 1, 0.75)])
print(DG.out_degree(1, weight='weight'))
#0.5
print(DG.in_degree(1, weight='weight'))
#0.75
print(DG.degree(1, weight='weight'))
#1.25
print(DG.successors(1))
#[2]
print(DG.neighbors(1))
#[2]
print(DG.out_edges(3))
#[(3, 1)]
print(DG.in_edges(2))
#[(1, 2)]
print(DG.predecessors(1))
[3]
'''
总结:
DiGraph.out_edges(), DiGraph.in_edges()
DiGraph.in_degree(), DiGraph.out_degree(),DiGraph.degree()
DiGraph.predecessors(),
DiGraph.successors()相当于DiGraph.neighbours()
''' H = nx.Graph(DG)#将有向图转化为无向图
print(H.edge)
# {1: {2: {'weight': 0.5}, 3: {'weight': 0.75}}, 2: {1: {'weight': 0.5}}, 3: {1: {'weight': 0.75}}} H1 = DG.to_undirected()
print(H1.edge)
#{1: {2: {'weight': 0.5}, 3: {'weight': 0.75}}, 2: {1: {'weight': 0.5}}, 3: {1: {'weight': 0.75}}}
MultiGraph:
任意一对nodes之间可以有多条边。边的属性不同
#任意一对nodes之间可以有多条边。边的属性不同
import networkx as nx
MG = nx.MultiGraph()
MG.add_weighted_edges_from([(1, 2, 0.5), (1, 2, 0.75), (2, 3, 0.5)]) print(MG.degree(weight='weight'))
#{1: 1.25, 2: 1.75, 3: 0.5} GG = nx.Graph()
for n, nbrs in MG.adj.items():
for nbr, edgeDict in nbrs.items():
minvalue = min([d['weight'] for d in edgeDict.values()])
GG.add_edge(n, nbr, weight=minvalue) print(nx.shortest_path(GG, 1, 3))
#[1, 2, 3] print(MG.adj.items())
#dict_items([(1, {2: {0: {'weight': 0.5}, 1: {'weight': 0.75}}}),
# (2, {1: {0: {'weight': 0.5}, 1: {'weight': 0.75}}, 3: {0: {'weight': 0.5}}}),
# (3, {2: {0: {'weight': 0.5}}})])
NetworkX包的更多相关文章
- python下的复杂网络编程包networkx的使用(摘抄)
原文:http://blog.sciencenet.cn/home.php?mod=space&uid=404069&do=blog&classid=141080&vi ...
- 网络分析之networkx(转载)
图的类型 Graph类是无向图的基类,无向图能有自己的属性或参数,不包含重边,允许有回路,节点可以是任何hash的python对象,节点和边可以保存key/value属性对.该类的构造函数为Graph ...
- python网络画图——networkX
networkX tutorial 绘制基本网络图 用matplotlib绘制网络图 基本流程: 1. 导入networkx,matplotlib包 2. 建立网络 3. 绘制网络 nx.draw() ...
- Python 学习 第十六篇:networkx
networkx是Python的一个包,用于构建和操作复杂的图结构,提供分析图的算法.图是由顶点.边和可选的属性构成的数据结构,顶点表示数据,边是由两个顶点唯一确定的,表示两个顶点之间的关系.顶点和边 ...
- 『Networkx』常用方法
这是一个用于分析'图'结构的包,由于我只是用到了浅显的可视化功能,所以这个介绍会对其使用浅尝辄止. 解决matplotlib中文字体缺失问题, from pylab import mpl mpl.rc ...
- [译]学习IPython进行交互式计算和数据可视化(三)
第二章 在本章中,我们将详细学习IPython相对以Python控制台带来的多种改进.特别的,我们将会进行下面的几个任务: 从IPython中使用系统shell以在shell和Python之间进行强大 ...
- 用python探索和分析网络数据
Edited by Markdown Refered from: John Ladd, Jessica Otis, Christopher N. Warren, and Scott Weingart, ...
- OTU_Network&calc_otu
# -*- coding: utf-8 -*- # __author__ = 'JieYap' from biocluster.agent import Agent from biocluster.t ...
- PageRank 算法-Google 如何给网页排名
公号:码农充电站pro 主页:https://codeshellme.github.io 在互联网早期,随着网络上的网页逐渐增多,如何从海量网页中检索出我们想要的页面,变得非常的重要. 当时著名的雅虎 ...
随机推荐
- Intellij IDEA 导入eclipse 项目
HoJe一个会rep的程序猿 . 感谢2019 时间匆匆,一转眼2019要跟我们说再见了.我们怀有太多的期望就难免遭遇失望和挫折.我们遇到了困难,往往不是想办法去解决,而是抱怨这个命运的不公.如果生活 ...
- golang编译之vendor机制
Go 1.5引入了vendor 机制,但是需要手动设置环境变量 GO15VENDOREXPERIMENT= 1,Go编译器才能启用.从Go1.6起,,默认开启 vendor 目录查找,vendor 机 ...
- 傅立叶变换—FFT(cuda实现)
背景: 无意间看到cuda解决FFT有一个cufft函数库,大体查看了有关cufft有关知识,写了一个解决一维情况的cuda代码,据调查知道cufft在解决1D,2D,3D的情况时间复杂度都为O(nl ...
- 前端页面表格排序 jQuery Table 基础
通常来说, 排序的方式有两种, 一种是我们在查询的时候就排好序,然后将数据渲染到前台页面上, 但是这样做有个弊端,就是在争对做好了缓存处理的系统, 在查询相同数据的时候进行排序,可能不能成功, 因为进 ...
- C# 根据链接提取div内容
安装NuGet包 HtmlAgilityPack var wc = new WebClient(); wc.Encoding = Encoding.GetEncoding("UTF-8 ...
- Spring Boot 入门(十):集成Redis哨兵模式,实现Mybatis二级缓存
本片文章续<Spring Boot 入门(九):集成Quartz定时任务>.本文主要基于redis实现了mybatis二级缓存.较redis缓存,mybaits自带缓存存在缺点(自行谷歌) ...
- Anaconda的CondaHTTPError问题
在Anaconda+Spyder配置Opencv的过程中遇到了缺乏cv2的问题,当时我在cmd的窗口(管理员身份)中输入了如下命令 conda install --channel https://co ...
- 位运算上的小技巧 - AtCoder
Problem Statement There is an integer sequence of length 2N: A0,A1,…,A2N−1. (Note that the sequence ...
- iOS的项目目录结构
一.一般面试官都会问这样的一个问题,你怎样划分你项目的目录结构,就能测试出这个人是否有经验? 目前,比较常规的两种结构: 1.主目录按照业务分类,内目录按照模块分类(主目录按照MVC架构分类,内部根据 ...
- 使用Oracle Stream Analytics 21步搭建大数据实时流分析平台
概要: Oracle Stream Analytics(OSA)是企业级大数据流实时分析计算平台.它可以通过使用复杂的关联模式,扩充和机器学习算法来自动处理和分析大规模实时信息.流式传输的大数据可以源 ...