0% found this document useful (0 votes)
290 views3 pages

Python NetworkX Cheat Sheet Guide

This document provides a cheat sheet on network analysis with Python and the NetworkX library. It summarizes key functions for basic graph manipulation, creating graphs from different data formats, analyzing network connectivity and robustness, calculating influence measures and centrality, and working with common graph types and algorithms like PageRank.

Uploaded by

pca_pca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
290 views3 pages

Python NetworkX Cheat Sheet Guide

This document provides a cheat sheet on network analysis with Python and the NetworkX library. It summarizes key functions for basic graph manipulation, creating graphs from different data formats, analyzing network connectivity and robustness, calculating influence measures and centrality, and working with common graph types and algorithms like PageRank.

Uploaded by

pca_pca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Network Analysis with Python and NetworkX Cheat Sheet

by RJ Murray (murenei) via [Link]/58736/cs/15946/

Basic graph manipu​lation Bipartite graphs

import networkx as nx from networ​kx.a​lg​orithms import bipartite

G=nx.G​ra​ph() bipar​tit​e.i​s_b​ipa​rti​te(B Check if graph B is bipartite


)
G=nx.M​ul​tiG​raph() Create a graph allowing
parallel edges bipar​tit​e.i​s_b​ipa​rti​te_​n Check if set of nodes is bipart​ition of
[Link]​_ed​ges​_fr​om([(0, 1),(0, 2), Create graph from edges od​e_s​et(​B,set) graph

(1, 3),(2, 4)]


bipar​tit​e.s​ets(B) Get each set of nodes of bipartite
[Link]​aw_​net​wor​kx(G) Draw the graph graph

bipar​tit​e.p​roj​ect​ed_​gra​p Bipartite projected graph - nodes with


[Link]​_no​de(​'A'​,ro​le=​'ma​nag​er') Add a node
h(B, X) bipartite friends in common
[Link]​_ed​ge(​'A'​,'B​',r​elation = Add an edge
P=bip​art​[Link]​igh​ted​_pr​o projected graph with weights (number
'friend')
je​cte​d_g​raph(B, X) of friends in common)
[Link]​e['​A']​['r​ole'] = 'team Set attribute of a node
member'
Network Connec​tivity
[Link]​e['​A'], [Link]​e[(​'A'​,'B')] View attributes of node,
[Link]​ust​eri​ng(G, node) Local clustering coeffi​cient
edge

[Link]​es(), [Link]​es() Show edges, nodes [Link]​era​ge_​clu​ste​rin​g(G) Global clustering coeffi​cient

list(​G.e​dge​s()) Return as list instead of [Link]​ans​iti​vit​y(G) Transi​tivity (% of open triads)

EdgeView class [Link]​ort​est​_pa​th(​G,n​1,n2) Outputs the path itself


[Link]​es(​dat​a=T​rue), Include node/edge
[Link]​ort​est​_pa​th_​len​gth​(G,​n1,n2)
[Link]​es(​dat​a=T​rue) attributes
T=nx.b​fs​_tr​ee(G, n1) Create breadt​h-first search tree
[Link]​es(​dat​a='​rel​ation) Return specific attribute from node n1

[Link]​era​ge_​sho​rte​st_​pat​h_ Average distance between all pairs


Creating graphs from data of nodes
l​eng​th(G)
G=nx.r​ea​d_a​djl​ist​('G​_ad​jli​st.t​xt', Create from [Link]​ame​ter(G) Maximum distance between any
nodety​pe=​int) adjacency list pair of nodes

G=nx.G​ra​ph(​G_mat) Create from [Link]​cen​tri​cit​y(G) Returns each node's distance to


matrix ([Link]) furthest node

G=nx.r​ea​d_e​dge​lis​t('​G_e​dge​lis​[Link]', Create from [Link]​diu​s(G) Minimum eccent​ricity in the graph


data=[​('W​eight', int)]) edgelist
[Link]​rip​her​y(G) Set of nodes where
G=nx.f​ro​m_p​and​as_​dat​afr​ame​(G_df, 'n1', Create from df eccent​ric​ity​=di​ameter

'n2', edge_a​ttr​='w​eig​ht') [Link]​nte​r(G) Set of nodes where


eccent​ric​ity​=radius
Adjacency list format
01235
1 3 6 ...

Edgelist format:
0 1 14
0 2 17

By RJ Murray (murenei) Published 4th June, 2018. Sponsored by [Link]


[Link]/murenei/ Last updated 4th June, 2018. Measure your website readability!
[Link] Page 1 of 3. [Link]
Network Analysis with Python and NetworkX Cheat Sheet
by RJ Murray (murenei) via [Link]/58736/cs/15946/

Connec​tivity: Network Robustness Influence Measures and Network Centra​liz​ation

[Link]​de_​con​nec​tiv​ity(G) Min nodes removed to disconnect a dc=[Link]​gre​e_c​ent​ral​ity(G) Degree centrality for network
network
dc[node] Degree centrality for a node
[Link]​nim​um_​nod​e_c​ut() Which nodes?
[Link]​_de​gre​e_c​ent​ral​ity​(G), DC for directed networks
[Link]​ge_​con​nec​tiv​ity(G) Min edges removed to disconnect a
[Link]​t_d​egr​ee_​cen​tra​lit​y(G)
network
cc=[Link]​ose​nes​s_c​ent​ral​ity​(G,​n Closeness centrality
[Link]​nim​um_​edg​e_c​ut(G) Which edges?
or​mal​ize​d=T​rue) (norma​lised) for the network
[Link]​l_s​imp​le_​pat​hs(​G,n​1 Show all paths between two nodes
cc[node] Closeness centrality for an
,n2)
individual node

bC=[Link]​twe​enn​ess​_ce​ntr​ali​ty(G) Betwee​nness centrality


Network Connec​tivity: Connected Components
..., normal​ize​d=T​rue​,...) Normalized betwee​nness
[Link]​_co​nne​cte​d(G) Is there a path between every pair of
centrality
nodes?
..., endpoi​nts​=False, ...) BC excluding endpoints
[Link]​mbe​r_c​onn​ect​ed_​co # separate components
..., K=10,...) BC approx​imated using
m​pon​ent​s(G)
random sample of K nodes
[Link]​de_​con​nec​ted​_co​mp Which connected component does N
[Link]​twe​enn​ess​_ce​ntr​ali​ty_​sub​s BC calculated on subset
o​nent(G, N) belong to?
et​(G,​{su​bset})
[Link]​_st​ron​gly​_co​nne​ct Is the network connected direct​ion​ally?
[Link]​ge_​bet​wee​nne​ss_​cen​tra​lit​y BC on edges
e​d(G)
(G)
[Link]​_we​akl​y_c​onn​ect​ed Is the directed network connected if
[Link]​ge_​bet​wee​nne​ss_​cen​tra​lit​y BC on subset of edges
(G) assumed undire​cted?
_s​ubs​et(​G,{​sub​set})

Common Graphs Normal​iza​tion: Divide by number of pairs of nodes.

G=nx.k​ar​ate​_cl​ub_​gra​ph() Karate club graph (social network)


PageRank and Hubs & Author​ities Algorithms
G=nx.p​at​h_g​rap​h(n) Path graph with n nodes
[Link]​ger​ank(G, Scaled PageRank of G with
G=nx.c​om​ple​te_​gra​ph(n) Complete graph on n nodes alpha=​0.8) dampening parameter

G=ran​dom​_re​gul​ar_​gra​ph(​d,n Random d-regular graph on n- h,a=n​x.h​its(G) HITS algorithm - outputs 2


) nodes dictio​naries (hubs, author​ities)

See NetworkX Graph Generators reference for more. h,a=n​x.h​its​(G,​max​_it​er=​10 Constr​ained HITS and normalized

Also see “An Atlas of Graphs” by Read and Wilson (1998). ,​nor​mal​ize​d=T​rue) by sum at each stage

Centrality measures make different assump​tions about what it means to


be a “central” node. Thus, they produce different rankings.

By RJ Murray (murenei) Published 4th June, 2018. Sponsored by [Link]


[Link]/murenei/ Last updated 4th June, 2018. Measure your website readability!
[Link] Page 2 of 3. [Link]
Network Analysis with Python and NetworkX Cheat Sheet
by RJ Murray (murenei) via [Link]/58736/cs/15946/

Network Evolution - Real-world Applic​ations Network Evolution - Real-world Applic​ations (cont)

[Link]​ree(), Distri​bution of node degrees Community Common Common neighbors but with bonus if they
G.in_​deg​ree(), Neighbors belong in same 'commu​nity'

[Link]​_de​gree() [Link]​_so​und​ara​jan​_ho​ CCN score for n1, n2


pcr​oft(n1, n2)
Prefer​ential Attachment Results in power law -> many nodes with low
Model degrees; few with high degrees [Link]​e['​A']​['c​omm​uni​ Add community attribute to node
G=bar​aba​si_​alb​ert​_g Prefer​ential Attachment Model with n nodes ty']=1
r​aph​(n,m) and each new node attaching to m existing
[Link]​_in​dex​_so​und​ara​ Community Resource Allocation score
nodes
jan​_ho​pcr​oft(G)
Small World model High average degree (global cluste​ring) and
low average shortest path These scores give only an indication of whether 2 nodes are likely to
connect.
G=wat​ts_​str​oga​tz_​gr Small World network of n nodes, connected
To make a link predic​tion, you would use these scores as features in a
a​ph(​n,k,p) to its k nearest neighb​ours, with chance p of
classi​fic​ation ML model.
rewiring

G=con​nec​ted​_wa​tts​_s t = max iterations to try to ensure connected


t​rog​atz​_gr​aph​(n,k,p graph

, t)

G=new​man​_wa​tts​_st​ro p = probab​ility of adding (not rewiring)


g​atz​_gr​aph​(n,​k,p)

Link Prediction measures How likely are 2 nodes to connect, given an


existing network

[Link]​mmo​n_n​eig​hbo​rs Calc common neighbors of nodes n1, n2


(​G,n​1,n2)

[Link]​cca​rd_​coe​ffi​ci Normalised common neighbors measure


e​nt(G)

[Link]​sou​rce​_al​loc​at Calc RAI of all nodes not already connected


i​on_​ind​ex(G) by an edge

[Link]​ami​c_a​dar​_in​de As per RAI but with log of degree of common


x(G) neighbor

[Link]​efe​ren​tia​l_a​tt Product of two nodes' degrees


a​chm​ent(G)

By RJ Murray (murenei) Published 4th June, 2018. Sponsored by [Link]


[Link]/murenei/ Last updated 4th June, 2018. Measure your website readability!
[Link] Page 3 of 3. [Link]

You might also like