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 在互联网早期,随着网络上的网页逐渐增多,如何从海量网页中检索出我们想要的页面,变得非常的重要. 当时著名的雅虎 ...
随机推荐
- Android短视频滑动播放(一)
本文主要介绍采用RecyclerView配合PagerSnapHelper实现短视频滑动播放内容. 1. 主页内容构建 主页布局文件定义RecyclerView,为RecyclerView建立对应适配 ...
- 1052 卖个萌 (20 分)C语言
萌萌哒表情符号通常由"手"."眼"."口"三个主要部分组成.简单起见,我们假设一个表情符号是按下列格式输出的: [左手]([左眼][口][右 ...
- Go Goosy Disk Docker Port Provisioners(GDP)
小伙伴们,她们中出了一个叛徒,他是谁?是谁?是谁? 由一则口口相传的故事开始吧: 中午吃饭时间抽空小李跑到同座大楼的小张公司串门,小李是一名docker顾问熟称砖家,这间公司老板想挖小李,他盯了前台不 ...
- Jaeger容器化部署
概述 Jaeger是由Uber开源的分布式追踪系统,一套完整的Jager追踪系统包括Jaeger-client.Jaeger-agent.Jaeger-collector.Database和Jaege ...
- 怎样使用七牛云CDN加速并绑定阿里云域名
昨天晚上在某个群里看到群友问,七牛云能不能绑定自己的域名作为静态资源文件的前缀,忽然想起来我已经有快两年时间没有登录过我的七牛云账号了,不禁老脸一红,这是有多久没有自己前后端都弄了,幸好还没有老年痴呆 ...
- 前端笔记5-js1
一.在JS中一共有6种数据类型1. String 字符串2. Number 数值3. Boolean 布尔值4. Null 空值5. Undefined 未定义6. Object 对象 其中 Stri ...
- scala 对一个数组分组操作
通常我们有一些需求,对一个数组两两进行翻转,通常就涉及到奇数偶数,否则就会出现数组index异常了,所以我们该怎么办呢? 虽然是一个入门级问题,但是我还是觉得这是一个很有意思的题目,因此写了一个对于通 ...
- Mysql 8+ 版本完全踩坑记录
问题是这样 刚霍霍了一台腾讯云服务器需要安装mysql 然后就选择了8+这个版本. 安装步骤网上有的是. 我只写最主要的部分 绝对不出错 外网可访问 .net java都可以调用 其实不指望有人看 就 ...
- vue-DevTools安装使用
方式一:通过谷歌应用商店进行安装 vue devtools 方式二:手动安装 下载https://github.com/vuejs/vue-devtools 安装 方式一:打开谷歌浏览器 点击扩展程 ...
- Python中类属性和实例属性的区别
在Python中经常会混淆类属性和实例属性的概念,今天专门记录一下个人理解以免日后忘记. 看下面的例子: class Tencent(): i = 10 # 此处i为类属性 def __init__( ...