Python & Data Science

Networkx Basics Modeling And Analyzing Relationshi

You’ve spent years working with data in tables. Every row is a customer, a product, or a transaction. Every column is an attribute. It’s clean, it’s familiar, and it works — until the question you’re asking isn’t about the rows themselves, but about how they’re connected.

Think about it: who influences whom in a social network? Which products are most likely to be bought together? How does a rumor spread through an organization? These questions are about relationships, not just individual records. And if you try to answer them with SQL joins or pandas merges, you’ll end up with a tangled mess of self-joins and recursive queries.

Let’s look at a tiny example. Here’s a list of friendships:

Person 1Person 2
AliceBob
BobCharlie
CharlieDiana
DianaAlice
AliceEve

If I ask you “who is the most central person in this group?” or “what’s the shortest chain connecting Alice to Charlie?”, you could probably figure it out by staring at the table for a minute. But what if there were 10,000 people and 50,000 friendships? That table becomes useless for understanding the shape of the connections.

What we need is a data structure that treats relationships as a first-class citizen — not as something we have to reconstruct from joins. That’s where NetworkX comes in.

Let’s start by importing it and creating our first graph.

import networkx as nx

# Create an empty graph
G = nx.Graph()

# Add some nodes (people)
G.add_nodes_from(['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'])

# Add edges (friendships)
G.add_edges_from([
    ('Alice', 'Bob'),
    ('Bob', 'Charlie'),
    ('Charlie', 'Diana'),
    ('Diana', 'Alice'),
    ('Alice', 'Eve')
])

print(f"Created a graph with {G.number_of_nodes()} nodes and {G.number_of_edges()} edges")
print(f"Nodes: {list(G.nodes())}")
print(f"Edges: {list(G.edges())}")

When you run this, you’ll see we’ve built a small social network. But it’s still just text. Let’s see what it actually looks like.

What is a graph? (And why should you care?)

In plain English, a graph is just a set of things (we call them nodes) and the connections between pairs of things (we call them edges). That’s it. No fancy math required.

Now here’s the interesting part: there are two flavors of graphs, and the difference matters.

  • Undirected graph: If Alice is friends with Bob, then Bob is automatically friends with Alice. The relationship is mutual. Think of it like a handshake — both people are involved.
  • Directed graph: If Alice follows Bob on Twitter, that doesn’t mean Bob follows Alice. The relationship has a direction. Think of it like a one-way street.

NetworkX handles both. By default, nx.Graph() creates an undirected graph. If you need directed, you’d use nx.DiGraph().

Let’s visualize our little social network so you can see the shape of the connections.

import matplotlib.pyplot as plt

# Create the same graph as before
G = nx.Graph()
G.add_nodes_from(['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'])
G.add_edges_from([
    ('Alice', 'Bob'),
    ('Bob', 'Charlie'),
    ('Charlie', 'Diana'),
    ('Diana', 'Alice'),
    ('Alice', 'Eve')
])

# Draw the graph
pos = nx.spring_layout(G, seed=42)  # positions for all nodes
nx.draw(G, pos, with_labels=True, node_color='lightblue', 
        node_size=500, font_size=12, font_weight='bold')
plt.title("A simple social network")
plt.show()

What do you see? Alice connects to Bob, Diana, and Eve. Bob connects to Alice and Charlie. Charlie connects to Bob and Diana. Notice how Bob sits between Alice and Charlie — he’s a bridge between those two clusters. That’s the kind of insight you’d never get from the table alone.

Putting data on the graph: attributes

“So we can draw lines — big deal,” you might be thinking. “How do we attach real data?”

The answer is simple: attributes. Every node and every edge can carry a dictionary of information, just like you already use in Python.

# Create a fresh graph with attributes
G = nx.Graph()

# Add nodes with attributes
G.add_node('Alice', age=30, department='Engineering')
G.add_node('Bob', age=28, department='Marketing')
G.add_node('Charlie', age=35, department='Engineering')
G.add_node('Diana', age=32, department='Sales')
G.add_node('Eve', age=27, department='Marketing')

# Add edges with attributes
G.add_edge('Alice', 'Bob', weight=5, relationship='colleague')
G.add_edge('Bob', 'Charlie', weight=3, relationship='friend')
G.add_edge('Charlie', 'Diana', weight=4, relationship='colleague')
G.add_edge('Diana', 'Alice', weight=2, relationship='friend')
G.add_edge('Alice', 'Eve', weight=1, relationship='mentor')

# View all node data
print("All nodes with attributes:")
for node, data in G.nodes(data=True):
    print(f"  {node}: {data}")

print("\nAll edges with attributes:")
for u, v, data in G.edges(data=True):
    print(f"  {u} -- {v}: {data}")

Now this graph is a rich data structure, not just a drawing. We can filter, group, and analyze using these attributes. For example, we could find all nodes in Engineering, or all edges with weight greater than 3.

What can we ask the graph?

Now that we have a graph with real data, let’s ask real questions. This is the hardest part: shifting your mental model from SQL/pandas to graph queries. You’re not asking for a filtered subset of rows — you’re asking about the shape of connections.

# Recreate the graph with attributes (self-contained block)
G = nx.Graph()
G.add_node('Alice', age=30)
G.add_node('Bob', age=28)
G.add_node('Charlie', age=35)
G.add_node('Diana', age=32)
G.add_node('Eve', age=27)

G.add_edge('Alice', 'Bob', weight=5)
G.add_edge('Bob', 'Charlie', weight=3)
G.add_edge('Charlie', 'Diana', weight=4)
G.add_edge('Diana', 'Alice', weight=2)
G.add_edge('Alice', 'Eve', weight=1)

# Basic queries
print(f"Number of nodes: {G.number_of_nodes()}")
print(f"Number of edges: {G.number_of_edges()}")

# List Alice's neighbors
print(f"\nAlice's neighbors: {list(G.neighbors('Alice'))}")
# Alice has 3 friends: Bob, Diana, and Eve

# Find the shortest path between two nodes
path = nx.shortest_path(G, 'Alice', 'Charlie')
print(f"Shortest path from Alice to Charlie: {path}")
# The shortest chain is 2 steps: Alice → Bob → Charlie

# Check if the graph is connected
print(f"Is the graph connected? {nx.is_connected(G)}")
# Yes, everyone can reach everyone else

# Find all connected components
print(f"Number of connected components: {nx.number_connected_components(G)}")

See what happened there? We asked “what’s the shortest chain from Alice to Charlie?” and got back ['Alice', 'Bob', 'Charlie']. In a table, you’d need to join the friendship table to itself multiple times to find that path. NetworkX does it in one function call.

The real power: graph algorithms that see what tables miss

Graphs are not just for drawing and simple queries. They shine when you use algorithms to uncover invisible patterns in the relationships. Two people might be far apart in the table but close in the graph — graph algorithms expose that.

Let’s look at two classic metrics.

# Recreate the graph (self-contained)
G = nx.Graph()
G.add_edges_from([
    ('Alice', 'Bob'),
    ('Bob', 'Charlie'),
    ('Charlie', 'Diana'),
    ('Diana', 'Alice'),
    ('Alice', 'Eve')
])

# Betweenness centrality: which nodes act as bridges?
betweenness = nx.betweenness_centrality(G)
print("Betweenness centrality (higher = more of a bridge):")
for node, score in sorted(betweenness.items(), key=lambda x: x[1], reverse=True):
    print(f"  {node}: {score:.3f}")

# Average clustering coefficient: how tight-knit are the groups?
clustering = nx.average_clustering(G)
print(f"\nAverage clustering coefficient: {clustering:.3f}")
# A value close to 1 means "my friends tend to be friends with each other"

Let’s interpret these numbers in plain English.

Betweenness centrality measures how often a node lies on the shortest path between other pairs of nodes. Bob has the highest score here because he connects Alice’s group to Charlie’s group. If you removed Bob, the network would split into two separate pieces. He’s the bridge.

Average clustering coefficient measures how tightly knit the groups are. A value of 1.0 would mean that every pair of my friends are also friends with each other. Our network has a moderate clustering value — some triangles exist (Alice-Bob-Diana form a triangle), but not everyone is connected to everyone else.

These metrics would be extremely difficult to compute from tabular data alone. With NetworkX, they’re one function call away.

Bringing your own data into a graph

You don’t need to type nodes by hand — you probably already have the data in a DataFrame. Here’s how to import it.

import pandas as pd
import networkx as nx

# Create an edge list DataFrame (like you'd have in a real dataset)
edges_df = pd.DataFrame({
    'source': ['Alice', 'Bob', 'Charlie', 'Diana', 'Alice'],
    'target': ['Bob', 'Charlie', 'Diana', 'Alice', 'Eve'],
    'weight': [5, 3, 4, 2, 1]
})

print("Edge list DataFrame:")
print(edges_df)

# Convert to a graph
G = nx.from_pandas_edgelist(edges_df, source='source', target='target', edge_attr='weight')

print(f"\nCreated graph with {G.number_of_nodes()} nodes and {G.number_of_edges()} edges")
print(f"Nodes: {list(G.nodes())}")

# Now you can also attach node attributes from another DataFrame
node_metadata = pd.DataFrame({
    'node': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'],
    'age': [30, 28, 35, 32, 27],
    'department': ['Engineering', 'Marketing', 'Engineering', 'Sales', 'Marketing']
})

# Add node attributes from the DataFrame
for _, row in node_metadata.iterrows():
    G.nodes[row['node']]['age'] = row['age']
    G.nodes[row['node']]['department'] = row['department']

print("\nNode attributes:")
for node, data in G.nodes(data=True):
    print(f"  {node}: {data}")

Now imagine you have a graph of 5,000 transactions and 1,500 products. All the queries and algorithms you just saw — neighbors, shortest paths, betweenness centrality — work exactly the same way. The size doesn’t change the code.

Where you are and where you’re going

Let’s recap what you’ve learned:

  • Created graphs with nodes and edges using NetworkX
  • Attached data to both nodes and edges using attributes
  • Ran basic queries like finding neighbors and shortest paths
  • Computed graph algorithms like betweenness centrality and clustering
  • Imported real data from pandas DataFrames using from_pandas_edgelist

You now have a new mental model for data — as relationships, not just rows. The next part of this series will use these same tools to find communities (like friend groups in social networks) and identify influencers (the most central nodes).

But first, let’s make sure the concepts stick.

Check Your Understanding

Remember: What does nx.Graph() create by default — an undirected or directed graph?

Understand: In your own words, explain what betweenness centrality measures. What would it mean if Bob had a betweenness score of 0.6?

Apply: Given this small edge list — [('Alice', 'Bob'), ('Bob', 'Charlie'), ('Charlie', 'Alice')] — write the NetworkX code to create the graph and find the shortest path between ‘Alice’ and ‘Charlie’.

Analyze: Why is nx.is_connected(G) useful when analyzing a social network dataset? What would you do if the graph is not connected?

Evaluate: Compare the strengths and weaknesses of storing the same data in a pandas DataFrame vs. a NetworkX graph. When would you choose one over the other?

Apply What You Learned

**Task**: Load any edge-list dataset you have into a NetworkX graph, or use the built-in Zachary's Karate Club dataset (`nx.karate_club_graph()`). Compute betweenness centrality for each node, then visualize the graph with node size proportional to centrality.

Deliverable: A single Python script that:

  1. Loads the graph
  2. Computes betweenness centrality
  3. Draws the graph with node sizes proportional to centrality scores

Self-check:

  • Did you compute betweenness centrality correctly? High-centrality nodes should sit between clusters.
  • Did you size the nodes visually for clarity? Large nodes should be the bridge nodes.
  • Can you name the top 3 bridge nodes in your graph?

You now have the foundation to start thinking about data as relationships. The next time you look at a table of transactions, followers, or interactions, ask yourself: “What would this look like as a graph?” The answer might surprise you.

  • Python Engineering Under review

    Beyond The Basics Method Chaining And The Pandas P

    df = pd.read_csv('https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv')

  • Python Engineering Under review

    Selenium For Data Collection Scraping The Sites Be

    quotes = soup.find_all('div', class_='quote') print(f'Number of quotes found: {len(quotes)}')

  • Python Engineering Under review

    Sending Automated Emails And Reports From A Python

    You just spent three hours building a beautiful pandas report. You cleaned the data, created a summary table, made a chart, and exported everything to a CSV file.

  • Python Engineering Under review

    Reinforcement Learning Algorithms Reference Which

    Before we name a single algorithm, we need to name the axes that separate them. Otherwise, you’re memorizing names without knowing why they differ—like learning the names of every screwdriver without knowing whether your screw is flathead or Phillips. Let’s fix that.

Looking for something else?

Search every article by title, summary or topic.