python-igraph安装及用外部文件创建图

igraph是一个复杂网络分析包,提供C/C++、R语言(主要用于统计分析、绘图、数据挖掘)、Python接口。本文介绍python-igraph安装及用外部文件创建图。

1. igraph安装

尽管可以从python官网下载第三包python-igraph 0.7自行安装,但我在实际安装过程,会有一些包依赖问题。最后找到一种很简单的igraph安装方法,如下:

sudo add-apt-repository ppa:igraph/ppa    # Add the Launchpad repository to apt
sudo apt-get update                       # update your package database 
sudo apt-get install python-igraph

2. igraph学习资料

感觉这方面的中文资料比较少,也许是因为NetworkX多一点。我现在主要还是看手册,如下:

3. 将文件导入igraph

很多时候,实验的数据来源于外部的数据集dataset,数据集经过一定处理后(如工具grep, awk, seq),得到一系列包含(点, 点, 权重)的行,举例如下:

1     3     18147
1     4     2961
1     5     101085
1     14    7

将文本文件导入igraph构造图,相关python源代码如下:

#! /usr/bin/python3

import igraph as ig

G = ig.Graph()
for line in open("sum_duration.txt") :
  strlist = line.split()
  n1 = strlist[0]
  n2 = strlist[1]
  weight = int(strlist[2])

  G.add_vertex(n1);
  G.add_vertex(n2);
  G.add_edge(n1, n2, weight=weight)

ig.plot(G)
  
print (G.is_weighted())  # 输出:True
print G["1", "3"]        # 输出:18147

相关API如下:

add_vertex(name=None, **kwds)
add_edge(source, target, **kwds)
赞赏

微信赞赏支付宝赞赏

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注