🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Graph Analytics with NetworkX: Centrality and Communities

⭐ Premium

Graph Analytics with NetworkX: Centrality and Communities

Many datasets are not tables. Fraud rings, citation networks, supply chains, identity linkages, and recommendation graphs encode entities as nodes and relationships as edges — and the questions people ask about them (who is most influential, which group is tightly knit, is this connection a bridge?) do not reduce to row-wise aggregation. Graph analytics is the toolbox for those questions, and NetworkX is the reference Python library for exploring them: pure Python, expressive APIs, and implementations of the classic algorithms taught in every network science course.

This lesson builds from constructing typed, attributed graphs to computing the three centralities that cover most practical needs, then detecting community structure with Louvain and label propagation. Along the way you will see why centrality choice encodes a hypothesis about influence, and how community detection differs from clustering tabular data.

What You'll Learn

  • 1Construct attributed, directed, and weighted graphs from Python data structures
  • 2Compute and interpret degree, betweenness, and PageRank centrality on real-shaped networks
  • 3Detect communities with Louvain modularity optimization and label propagation
  • 4Choose the right centrality and resolution for a given business question

Prerequisites

  • !Python and pandas fluency
  • !Basic linear algebra (matrices, eigenvalues) for PageRank intuition
  • !Comfort reading network diagrams

Building graphs that carry meaning

A graph is nodes, edges, and optionally attributes on both. NetworkX keeps attributes in dicts, so a node can carry a role and an edge can carry a weight, direction, and timestamp without changing the underlying structure.

python
import networkx as nx
import pandas as pd

# Edges with weights and a relationship type
edges = pd.DataFrame([
    ("alice", "bob", 3.0, "collaborates"),
    ("alice", "carol", 1.0, "follows"),
    ("bob", "carol", 2.0, "collaborates"),
    ("bob", "dave", 5.0, "collaborates"),
    ("carol", "erin", 1.0, "follows"),
    ("dave", "erin", 2.0, "follows"),
    ("erin", "frank", 4.0, "collaborates"),
    ("frank", "alice", 1.0, "follows"),
    ("grace", "dave", 1.0, "follows"),
    ("grace", "frank", 2.0, "collaborates"),
], columns=["src", "dst", "weight", "rel"])

G = nx.from_pandas_edgelist(
    edges, source="src", target="dst",
    edge_attr=["weight", "rel"], create_using=nx.DiGraph()
)

roles = {"alice": "pm", "bob": "eng", "carol": "eng", "dave": "lead",
         "erin": "analyst", "frank": "lead", "grace": "new"}
nx.set_node_attributes(G, roles, "role")

print(f"Directed: {G.is_directed()}, nodes={G.number_of_nodes()}, "
      f"edges={G.number_of_edges()}")
print(f"Weighted degree of dave: {G.degree('dave', weight='weight')}")
print(f"Neighbors of alice (out): {list(G.successors('alice'))}")

Choose DiGraph when direction matters (follows, citations, transactions) — many centrality measures have direction-aware and undirected variants, and mixing them changes conclusions. For most influence questions on social-like data, keep the graph directed; convert to undirected only when the relationship is symmetric by nature.

StructureUse whenKey caution
Undirected GraphMutual relationships (co-authorship)Direction lost; fine if symmetric
Directed DiGraphAsymmetric ties (follows, money flow)Use in/out variants of centrality
MultiGraphParallel edges (multiple transactions)Some algorithms unsupported; aggregate first
WeightedStrength matters (dose, amount, frequency)Decide: weight as strength or as distance

A recurring design decision is whether weight means strength (more = closer) or distance (more = farther). Shortest-path algorithms expect distance; NetworkX's centrality functions take a distance parameter so you can pass 1/weight when your weights are strengths. Getting this backwards silently inverts every ranking.

Centrality: three questions, three answers

Degree centrality counts neighbors — local popularity, the crudest but fastest signal. Betweenness centrality counts shortest paths passing through a node — brokerage and control of flow, the measure that finds bridges between clusters. PageRank models a random walker with teleportation — recursive prestige, where a node matters if important nodes point at it.

python
import networkx as nx

deg = nx.degree_centrality(G)
bet = nx.betweenness_centrality(G, weight="weight", normalized=True)
pr = nx.pagerank(G, alpha=0.85, weight="weight")

rank = pd.DataFrame({"degree": deg, "betweenness": bet, "pagerank": pr})
print(rank.sort_values("pagerank", ascending=False).round(4))

# Top bridge node — usually the interesting fraud/influence lead
top_bridge = max(bet, key=bet.get)
print(f"Top bridge: {top_bridge} (betweenness={bet[top_bridge]:.3f})")

Interpret the disagreement between measures rather than averaging them. A node with high degree but low betweenness is a hub inside one cluster — well connected, not structurally essential. High betweenness with moderate degree is the classic bridge: removing it disconnects communities, which in fraud analysis marks a mule or orchestrator connecting otherwise separate rings. High PageRank with lower degree marks a quiet authority that prestigious nodes cite — an expert referenced by other experts.

For directed graphs, use in-degree for "who is cited" and out-degree for "who cites"; nx.pagerank already respects direction by default. For very large graphs, exact betweenness is expensive (roughly cubic); sample source nodes (k= parameter) for an approximate ranking that is usually sufficient for prioritization.

Community detection: finding the groups

Tabular clustering groups rows by feature similarity; community detection groups nodes so that edges are dense inside groups and sparse between them. Louvain optimizes modularity — a score comparing actual intra-community edges to what a random graph with the same degrees would produce — by greedily moving nodes between communities across iterations. Label propagation is a faster, near-linear heuristic where nodes repeatedly adopt the majority label of their neighbors until consensus.

python
import networkx as nx
from networkx.algorithms.community import louvain_communities, label_propagation_communities
from networkx.algorithms.community.quality import modularity

# Work on the undirected projection for community structure
U = G.to_undirected()

louvain_sets = louvain_communities(U, weight="weight", resolution=1.0, seed=42)
print("Louvain communities:")
for i, comm in enumerate(louvain_sets):
    print(f"  {i}: {sorted(comm)} (size={len(comm)})")
print(f"Louvain modularity: {modularity(U, louvain_sets, weight='weight'):.4f}")

label_sets = list(label_propagation_communities(U))
print("Label-propagation communities:", [sorted(c) for c in label_sets])

# Resolution sweep: smaller resolution = fewer, larger communities
for res in [0.5, 1.0, 1.5, 2.0]:
    comm = louvain_communities(U, weight="weight", resolution=res, seed=42)
    q = modularity(U, comm, weight="weight")
    print(f"resolution={res}: k={len(comm)}, modularity={q:.4f}")

The resolution parameter controls granularity: below 1.0 merges communities, above 1.0 splits them. There is no universally correct value — pick it against the question (detect a few broad segments, or many fine-grained fraud cells) and report the modularity at the chosen resolution. Louvain is stochastic; always set a seed and consider consensus across runs for high-stakes findings.

Label propagation is faster and useful as a sanity check: if two very different methods agree on the partition, confidence is higher. Disagreement usually flags ambiguous boundary nodes — exactly the ones worth manual review.

From centrality to features: graph signals in downstream ML

Centrality and community assignments are rarely the final deliverable; they become features in fraud, churn, and recommendation models. Degree, betweenness, PageRank, and community ID join the tabular feature matrix so a gradient boosting model can learn nonlinear combinations with behavioral and demographic signals. Two details matter for correctness. First, compute graph features only on a training snapshot that excludes the prediction window — leaking future edges into centrality creates a target leak that inflates offline metrics and collapses online. Second, normalize community IDs across snapshots by node-overlap matching, since integer labels are arbitrary and stochastic; raw IDs fed to a model mean nothing after retraining.

Graph embeddings such as node2vec and DeepWalk compress neighborhood structure into dense vectors that capture roles which single centralities miss — a fraud mule bridging two clusters may not top any one centrality ranking while its embedding sits between the two community centroids. When the downstream model is a tree ensemble, centrality features usually suffice; when it is a neural model trained on ample graph data, end-to-end GNN embeddings often win. Start with interpretable centralities; graduate to embeddings only when the added lift justifies the loss of explainability that auditors will ask for.

A worked triage workflow: prioritizing accounts

Tie the pieces together on a realistic fraud-adjacent workflow. Start with a transaction graph: accounts as nodes, transfers as weighted directed edges. Extract the undirected projection with aggregate transfer volume as weight, then compute degree, betweenness, and PageRank on the cleaned backbone so spurious micro-transfers do not dominate rankings. Run Louvain at a moderate resolution to segment the population; compute within-community density and cross-community edge counts for each account.

Rank accounts by a composite that weights cross-community betweenness heavily, since mules bridge rings, and flags accounts whose community membership flips between weekly snapshots, a sign of newly activated handlers. Export the top decile with their feature vectors to a case management queue, and feed the resolved labels back as ground truth to recalibrate the composite weights monthly. The graph analytics did not decide guilt; they ordered human review capacity, which is the realistic role of centrality and community detection in most production fraud systems.

Practical patterns: backbones, temporal graphs, and scale

Real networks are noisy. A backbone extraction keeps only edges whose weights are statistically surprising relative to a null model, cleaning the graph before centrality. Temporal graphs (edges with timestamps) let you compute centrality on sliding windows to catch a mule who only recently connected two rings — static aggregates hide that.

For scale, NetworkX is in-memory pure Python and comfortable to a few million edges on a beefy box. Beyond that, sample for centrality, push community detection to specialized libraries (igraph, graph-tool, or a graph database's built-ins), or partition with METIS-style cutters before running local algorithms. The workflow rarely needs all-pairs anything: compute the specific centralities on the specific slices that answer the business question, and persist those scores as features for downstream models — graph embeddings and GNNs (covered in a later lesson) take over when you need predictive structure rather than interpretability.

Common Mistakes

Using weight as distance when it represents strength

Fix: Pass distance=1/weight (or invert explicitly) to shortest-path-based measures; verify rankings on a tiny hand-checked example first.

Running Louvain once with default resolution and trusting the partition

Fix: Sweep resolution, set the seed, compare against label propagation, and report modularity; single default runs hide instability.

Computing exact betweenness on a million-node graph and waiting hours

Fix: Sample sources (k parameter) or restrict to a relevant subgraph; approximate rankings are usually enough for prioritization.

Treating community IDs as meaningful labels across runs

Fix: Community IDs are arbitrary and stochastic; match communities across runs by node overlap, not by integer label.

Best Practices

  • Store edge semantics (strength vs distance, direction) in code comments and edge attributes so every analyst interprets weights the same way
  • Compute degree, betweenness, and PageRank together and inspect disagreements — the tension between measures is the insight
  • Set seeds for all stochastic community methods and report modularity alongside the partition
  • Extract a statistical backbone before centrality on noisy transaction graphs to avoid ranking on spurious edges
  • Persist centrality and community assignments as node features for downstream ML rather than recomputing ad hoc

Interview Questions

Q1: When is betweenness centrality more useful than degree for fraud detection?

Degree finds hubs; betweenness finds bridges. In fraud, orchestrators often connect otherwise separate low-degree clusters — high betweenness with modest degree — which degree-based ranking misses entirely.

Q2: What does modularity measure, and what is its limitation?

Modularity scores how much denser communities are than a degree-preserving random graph. Its limitation is resolution limit: it cannot detect communities much smaller than a scale determined by total edge weight, so fine structure vanishes at default settings.

Q3: Why does PageRank often beat raw in-degree for influence?

In-degree counts citations equally; PageRank weights a citation from an already-influential node more heavily, capturing recursive prestige and down-weighting spam-like fan-in from low-authority nodes.

Key Takeaways

  • NetworkX models attributed, directed, weighted graphs with a simple API; edge semantics (strength vs distance) must be explicit
  • Degree, betweenness, and PageRank answer different questions — local popularity, brokerage, recursive prestige — and their disagreements are the signal
  • Louvain optimizes modularity with a resolution knob; label propagation is a fast consensus check; both need seeds and reported modularity
  • Approximate centrality and backbone extraction make large graphs tractable without changing prioritization decisions
  • Persist graph-derived features (centrality, community IDs) for downstream models; use GNNs when structure is predictive rather than explanatory
🔒

Premium Content

Graph Analytics with NetworkX: Centrality and Communities

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Advertisement