Network Analysis with Python and NetworkX Cheat Sheet
by RJ Murray (murenei) via cheatography.com/58736/cs/15946/
Basic graph manipulation Bipartite graphs
import networkx as nx from networkx.algorithms import bipartite
G=nx.Graph() bipartite.is_bipartite(B Check if graph B is bipartite
)
G=nx.MultiGraph() Create a graph allowing
parallel edges bipartite.is_bipartite_n Check if set of nodes is bipartition of
G.add_edges_from([(0, 1),(0, 2), Create graph from edges ode_set(B,set) graph
(1, 3),(2, 4)]
bipartite.sets(B) Get each set of nodes of bipartite
nx.draw_networkx(G) Draw the graph graph
bipartite.projected_grap Bipartite projected graph - nodes with
G.add_node('A',role='manager') Add a node
h(B, X) bipartite friends in common
G.add_edge('A','B',relation = Add an edge
P=bipartite.weighted_pro projected graph with weights (number
'friend')
jected_graph(B, X) of friends in common)
G.node['A']['role'] = 'team Set attribute of a node
member'
Network Connectivity
G.node['A'], G.edge[('A','B')] View attributes of node,
nx.clustering(G, node) Local clustering coefficient
edge
G.edges(), G.nodes() Show edges, nodes nx.average_clustering(G) Global clustering coefficient
list(G.edges()) Return as list instead of nx.transitivity(G) Transitivity (% of open triads)
EdgeView class nx.shortest_path(G,n1,n2) Outputs the path itself
G.nodes(data=True), Include node/edge
nx.shortest_path_length(G,n1,n2)
G.edges(data=True) attributes
T=nx.bfs_tree(G, n1) Create breadth-first search tree
G.nodes(data='relation) Return specific attribute from node n1
nx.average_shortest_path_ Average distance between all pairs
Creating graphs from data of nodes
length(G)
G=nx.read_adjlist('G_adjlist.txt', Create from nx.diameter(G) Maximum distance between any
nodetype=int) adjacency list pair of nodes
G=nx.Graph(G_mat) Create from nx.eccentricity(G) Returns each node's distance to
matrix (np.array) furthest node
G=nx.read_edgelist('G_edgelist.txt', Create from nx.radius(G) Minimum eccentricity in the graph
data=[('Weight', int)]) edgelist
nx.periphery(G) Set of nodes where
G=nx.from_pandas_dataframe(G_df, 'n1', Create from df eccentricity=diameter
'n2', edge_attr='weight') nx.center(G) Set of nodes where
eccentricity=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 Readability-Score.com
cheatography.com/murenei/ Last updated 4th June, 2018. Measure your website readability!
tutify.com.au Page 1 of 3. https://readability-score.com
Network Analysis with Python and NetworkX Cheat Sheet
by RJ Murray (murenei) via cheatography.com/58736/cs/15946/
Connectivity: Network Robustness Influence Measures and Network Centralization
nx.node_connectivity(G) Min nodes removed to disconnect a dc=nx.degree_centrality(G) Degree centrality for network
network
dc[node] Degree centrality for a node
nx.minimum_node_cut() Which nodes?
nx.in_degree_centrality(G), DC for directed networks
nx.edge_connectivity(G) Min edges removed to disconnect a
nx.out_degree_centrality(G)
network
cc=nx.closeness_centrality(G,n Closeness centrality
nx.minimum_edge_cut(G) Which edges?
ormalized=True) (normalised) for the network
nx.all_simple_paths(G,n1 Show all paths between two nodes
cc[node] Closeness centrality for an
,n2)
individual node
bC=nx.betweenness_centrality(G) Betweenness centrality
Network Connectivity: Connected Components
..., normalized=True,...) Normalized betweenness
nx.is_connected(G) Is there a path between every pair of
centrality
nodes?
..., endpoints=False, ...) BC excluding endpoints
nx.number_connected_co # separate components
..., K=10,...) BC approximated using
mponents(G)
random sample of K nodes
nx.node_connected_comp Which connected component does N
nx.betweenness_centrality_subs BC calculated on subset
onent(G, N) belong to?
et(G,{subset})
nx.is_strongly_connect Is the network connected directionally?
nx.edge_betweenness_centrality BC on edges
ed(G)
(G)
nx.is_weakly_connected Is the directed network connected if
nx.edge_betweenness_centrality BC on subset of edges
(G) assumed undirected?
_subset(G,{subset})
Common Graphs Normalization: Divide by number of pairs of nodes.
G=nx.karate_club_graph() Karate club graph (social network)
PageRank and Hubs & Authorities Algorithms
G=nx.path_graph(n) Path graph with n nodes
nx.pagerank(G, Scaled PageRank of G with
G=nx.complete_graph(n) Complete graph on n nodes alpha=0.8) dampening parameter
G=random_regular_graph(d,n Random d-regular graph on n- h,a=nx.hits(G) HITS algorithm - outputs 2
) nodes dictionaries (hubs, authorities)
See NetworkX Graph Generators reference for more. h,a=nx.hits(G,max_iter=10 Constrained HITS and normalized
Also see “An Atlas of Graphs” by Read and Wilson (1998). ,normalized=True) by sum at each stage
Centrality measures make different assumptions about what it means to
be a “central” node. Thus, they produce different rankings.
By RJ Murray (murenei) Published 4th June, 2018. Sponsored by Readability-Score.com
cheatography.com/murenei/ Last updated 4th June, 2018. Measure your website readability!
tutify.com.au Page 2 of 3. https://readability-score.com
Network Analysis with Python and NetworkX Cheat Sheet
by RJ Murray (murenei) via cheatography.com/58736/cs/15946/
Network Evolution - Real-world Applications Network Evolution - Real-world Applications (cont)
G.degree(), Distribution of node degrees Community Common Common neighbors but with bonus if they
G.in_degree(), Neighbors belong in same 'community'
G.out_degree() nx.cn_soundarajan_ho CCN score for n1, n2
pcroft(n1, n2)
Preferential Attachment Results in power law -> many nodes with low
Model degrees; few with high degrees G.node['A']['communi Add community attribute to node
G=barabasi_albert_g Preferential Attachment Model with n nodes ty']=1
raph(n,m) and each new node attaching to m existing
nx.ra_index_soundara Community Resource Allocation score
nodes
jan_hopcroft(G)
Small World model High average degree (global clustering) and
low average shortest path These scores give only an indication of whether 2 nodes are likely to
connect.
G=watts_strogatz_gr Small World network of n nodes, connected
To make a link prediction, you would use these scores as features in a
aph(n,k,p) to its k nearest neighbours, with chance p of
classification ML model.
rewiring
G=connected_watts_s t = max iterations to try to ensure connected
trogatz_graph(n,k,p graph
, t)
G=newman_watts_stro p = probability of adding (not rewiring)
gatz_graph(n,k,p)
Link Prediction measures How likely are 2 nodes to connect, given an
existing network
nx.common_neighbors Calc common neighbors of nodes n1, n2
(G,n1,n2)
nx.jaccard_coeffici Normalised common neighbors measure
ent(G)
nx.resource_allocat Calc RAI of all nodes not already connected
ion_index(G) by an edge
nx.adamic_adar_inde As per RAI but with log of degree of common
x(G) neighbor
nx.preferential_att Product of two nodes' degrees
achment(G)
By RJ Murray (murenei) Published 4th June, 2018. Sponsored by Readability-Score.com
cheatography.com/murenei/ Last updated 4th June, 2018. Measure your website readability!
tutify.com.au Page 3 of 3. https://readability-score.com