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 在互联网早期,随着网络上的网页逐渐增多,如何从海量网页中检索出我们想要的页面,变得非常的重要. 当时著名的雅虎 ...
随机推荐
- ElementUi 两个表格反选
ElementUi 两个表格反选 1.先看看实现的图 表格内容显示 <el-row :gutter="20"> <el-col :span="16&qu ...
- Java Linked集合的简单介绍和常用方法的使用
LinkedList的简单介绍 java.util.LinkedList 集合数据存储的结构是链表结构.LinkedList是一个双向链表在实际开发中,对一个集合元素的添加和删除,经常涉及到首尾操作, ...
- cf 450b 矩阵快速幂(数论取模 一大坑点啊)
Jzzhu has invented a kind of sequences, they meet the following property: You are given x and y, ple ...
- 枚举 xor
题意:输入整数n(1<=n<=3千万),有多少对整数(a,b)满足:1<=b<=a<=n,且gcd(a,b)=a XOR b.例如:n=7时,有4对:(3,2),(5,4 ...
- Jquery电子签名制作_jSignature
今天用Jquery的jSignature库制作一个电子签名 后台.net core上传到指定文件夹 下载jquery库 提取码:rd9g html @{ Layout = null; } <!D ...
- Python Global和Nonlocal的用法
nonlocal 和 global 也很容易混淆.简单记录下自己的理解. 解释 global 总之一句话,作用域是全局的,就是会修改这个变量对应地址的值. global 语句是一个声明,它适用于整个当 ...
- python super()函数:调用父类的构造方法
python子类会继承父类所有的类属性和类方法.严格来说,类的构造方法其实就是实例方法,因此,父类的构造方法,子类同样会继承. 我们知道,python是一门支持多继承的面向对象编程语言,如果子类继承的 ...
- 异步查询转同步加redis业务实现的BUG分享
在最近的性能测试中,某一个查询接口指标不通过,开发做了N次优化,最终的优化方案如下:异步查询然后转同步,再加上redis缓存.此为背景. 在测试过程中发现一个BUG:同样的请求在第一次查询结果是OK的 ...
- Python环境搭建(win)——Python官方解释器
Python官方解释器搭建方法: 本文以当前最新的3.8.1为例 1.在电脑上打开Python的官网https://www.python.org/ 2.找到Download下的All releases ...
- selenium常见的元素定位方法
一.获取元素 1)通过谷歌浏览器自动的工具访问百度首页,我们可以看到,页面上的元素都是由一行行的代码组成的,它们之间有层级地组织起来,每个元素之间都有不同的标签和值,我们可以通过这些不同的标签和值来找 ...