Posts to networks¶
Social media data usually comes as a table of posts, not as a network. This notebook builds four networks from ten hand-written posts: a user-hashtag network, its projection onto the accounts, a hashtag co-occurrence network, and a reply network. It then finds the connected components of a network and saves a network to a file. The same code works for other posts that have the same four columns.
Sections: The posts, Extract the hashtags, User-hashtag network, Projection onto the accounts, Hashtag co-occurrence network, Reply network, Connected components, Save the network.
Packages beyond the standard library: networkx, pandas, matplotlib.
Install them with uv add networkx pandas matplotlib (or pip install).
Colab already has all three.
The notebook downloads no data.
import collections
import itertools
import pathlib
import re
import matplotlib.pyplot as plt
import networkx as nx
import pandas as pd
The posts¶
The ten posts are hand-written. No post, account, or hashtag comes from real data.
Each post has four fields.
post_id: the ID of the post.author: the account that wrote the post.reply_to: thepost_idof the post that this post replies to. It is empty for a post that is not a reply.text: the text of the post.
In the cell, None marks an empty value.
astype({"reply_to": "Int64"}) keeps the IDs in this column as integers, although some values are empty.
posts = pd.DataFrame(
[
(1, "alice", None, "Drew my first network today #python #networks"),
(2, "bob", 1, "@alice which layout did you use? #networks"),
(3, "carol", None, "A chart of follower counts on a log axis #dataviz #python"),
(4, "dave", 3, "@carol the log axis helps a lot #dataviz"),
(5, "alice", 3, "@carol can you share the code? #python #dataviz"),
(6, "erin", None, "Foggy trail this morning #hiking #coffee"),
(7, "frank", 6, "@erin which trail is this? #hiking"),
(8, "grace", None, "Saw a heron at the lake #birds #hiking"),
(9, "erin", 8, "@grace great photo #birds"),
(10, "heidi", None, "Testing my new account"),
],
columns=["post_id", "author", "reply_to", "text"],
).astype({"reply_to": "Int64"})
posts
print(len(posts), posts.author.nunique())
The table has 10 posts by 8 accounts.
Extract the hashtags¶
A hashtag is a # sign followed by letters, digits, or underscores.
The regular expression #\w+ finds every hashtag in a text.
The function changes the text to lowercase first, so #Python and #python count as the same hashtag.
def extract_hashtags(text):
return re.findall(r"#\w+", text.lower())
posts["hashtags"] = posts.text.apply(extract_hashtags)
posts[["author", "hashtags"]]
The new column holds a list of hashtags for each post. The first three rows:
| author | hashtags | |
|---|---|---|
| 0 | alice | [#python, #networks] |
| 1 | bob | [#networks] |
| 2 | carol | [#dataviz, #python] |
The post of heidi has an empty list.
explode turns each list into rows, so the table gets one row for each pair of a post and a hashtag.
A post with an empty list gets one row with an empty value, and dropna removes it.
uses = posts.explode("hashtags").dropna(subset=["hashtags"])
uses = uses.rename(columns={"hashtags": "hashtag"})[["post_id", "author", "hashtag"]]
len(uses)
The table uses has 14 rows: the ten posts use a hashtag 14 times.
Now count how many posts of each account use each hashtag.
user_hashtag = uses.groupby(["author", "hashtag"]).size().reset_index(name="weight")
len(user_hashtag)
The table user_hashtag has 13 rows, one for each pair of an account and a hashtag.
The first three rows:
| author | hashtag | weight | |
|---|---|---|---|
| 0 | alice | #dataviz | 1 |
| 1 | alice | #networks | 1 |
| 2 | alice | #python | 2 |
alice used #python in two posts, so this pair has the weight 2.
Every other pair has the weight 1.
User-hashtag network¶
A bipartite network has two sets of nodes, and every edge connects a node of one set and a node of the other set. Here one set holds the accounts and the other set holds the hashtags. An edge connects an account and a hashtag that the account used. The weight of an edge is the number of posts.
By convention, NetworkX marks the two sets with a node attribute named bipartite, with the values 0 and 1.
The hashtag nodes keep the # sign, so a hashtag and an account can never have the same node name.
accounts = uses.author.unique().tolist()
hashtags = uses.hashtag.unique().tolist()
user_hashtag_g = nx.Graph()
user_hashtag_g.add_nodes_from(accounts, bipartite=0)
user_hashtag_g.add_nodes_from(hashtags, bipartite=1)
user_hashtag_g.add_weighted_edges_from(user_hashtag.itertuples(index=False, name=None))
print(user_hashtag_g.number_of_nodes(), user_hashtag_g.number_of_edges())
The network has 13 nodes (7 accounts and 6 hashtags) and 13 edges.
add_weighted_edges_from takes triples of two nodes and a weight.
itertuples(index=False, name=None) turns each row of the table into such a triple.
heidi used no hashtag, so she is not in this network.
print(nx.is_bipartite(user_hashtag_g))
print(user_hashtag_g["alice"]["#python"]["weight"])
nx.is_bipartite returns True.
The edge between alice and #python has the weight 2.
The next cell draws the network with the accounts in the left column and the hashtags in the right column.
The code sets the positions by hand: each node gets an x value for its column and a y value for its row.
nx.bipartite_layout also makes two columns, but the order of the nodes in a column can change from run to run.
The width of an edge shows its weight.
pos = {}
for i, account in enumerate(accounts):
pos[account] = (0, -i)
for i, hashtag in enumerate(hashtags):
pos[hashtag] = (1, -i)
plt.figure(figsize=(6, 5.5))
nx.draw(
user_hashtag_g,
pos=pos,
with_labels=True,
node_color=["#9ecae1" if v in accounts else "#fdd0a2" for v in user_hashtag_g],
node_size=2000,
font_size=10,
width=[1.5 * w for _, _, w in user_hashtag_g.edges(data="weight")],
edge_color="#888888",
)
plt.margins(0.15)
plt.show()
The picture shows two groups.
The accounts alice, bob, carol, and dave use #python, #networks, and #dataviz.
The accounts erin, frank, and grace use #hiking, #coffee, and #birds.
No edge connects the two groups.
Projection onto the accounts¶
A projection turns a bipartite network into a network with one kind of node. In the projection onto the accounts, two accounts are connected if they used the same hashtag.
nx.bipartite.weighted_projected_graph builds the projection.
The weight of an edge is the number of hashtags that the two accounts share.
The function does not use the weights of the user-hashtag network.
account_g = nx.bipartite.weighted_projected_graph(user_hashtag_g, accounts)
print(account_g.number_of_nodes(), account_g.number_of_edges())
print(account_g["alice"]["carol"]["weight"])
The projection has 7 nodes and 7 edges.
alice and carol share 2 hashtags, #python and #dataviz.
The next cell draws the projection.
nx.circular_layout puts the nodes on a circle, in the order of the nodes of the network.
It has no random step, so it needs no seed.
nx.draw_networkx_edge_labels writes the weight on each edge.
pos = nx.circular_layout(account_g)
plt.figure(figsize=(6, 5))
nx.draw(
account_g,
pos=pos,
with_labels=True,
node_color="#9ecae1",
node_size=1800,
font_size=11,
edge_color="#888888",
)
nx.draw_networkx_edge_labels(
account_g,
pos,
edge_labels=nx.get_edge_attributes(account_g, "weight"),
font_size=12,
rotate=False,
)
plt.margins(0.1)
plt.show()
The first group has four accounts and four edges. The second group has three accounts and three edges.
Hashtag co-occurrence network¶
In a co-occurrence network, two hashtags are connected if they appear in the same post. The weight of an edge is the number of such posts.
itertools.combinations(tags, 2) returns every pair of the hashtags of one post.
sorted(set(tags)) removes a hashtag that a post uses twice.
It also puts the hashtags in a fixed order, so the pairs (a, b) and (b, a) are counted together.
A Counter counts each pair over all posts.
pair_counts = collections.Counter()
for tags in posts.hashtags:
for pair in itertools.combinations(sorted(set(tags)), 2):
pair_counts[pair] += 1
cooccurrence_g = nx.Graph()
cooccurrence_g.add_nodes_from(hashtags)
cooccurrence_g.add_weighted_edges_from((a, b, n) for (a, b), n in pair_counts.items())
print(cooccurrence_g.number_of_nodes(), cooccurrence_g.number_of_edges())
print(cooccurrence_g["#python"]["#dataviz"]["weight"])
The network has 6 nodes and 4 edges.
#python and #dataviz appear together in 2 posts.
add_nodes_from(hashtags) adds every hashtag as a node.
A hashtag that never appears together with another hashtag is then a node with no edge.
This network is not the same as the projection of the user-hashtag network onto the hashtags. The projection connects two hashtags if one account used both, also in two different posts. The next cell builds the projection and lists the edges that only the projection has.
hashtag_g = nx.bipartite.weighted_projected_graph(user_hashtag_g, hashtags)
print(hashtag_g.number_of_edges())
print(sorted(nx.difference(hashtag_g, cooccurrence_g).edges()))
The projection has 6 edges, two more than the co-occurrence network.
The two extra edges connect #coffee with #birds, and #networks with #dataviz.
erin used #coffee and #birds in two different posts.
alice used #networks and #dataviz in two different posts.
Use the co-occurrence network to ask which hashtags appear in the same post. Use the projection to ask which hashtags the same accounts use.
Reply network¶
A reply network is a directed network. An edge goes from the account that replies to the account that wrote the original post.
The reply network comes from the column reply_to.
The code does not read the mentions in the text, such as @alice.
The column reply_to holds the ID of a post, so the first step finds the author of that post.
author_of maps each post_id to its author.
author_of = posts.set_index("post_id").author
replies = posts.dropna(subset=["reply_to"]).copy()
replies["original_author"] = replies.reply_to.map(author_of)
replies[["author", "original_author"]]
Five of the ten posts are replies. The first three rows:
| author | original_author | |
|---|---|---|
| 1 | bob | alice |
| 3 | dave | carol |
| 4 | alice | carol |
In collected data, the original post can be missing from the table.
map then gives an empty value for the original author, and you have to drop these rows before the next step.
Now count the replies of each pair of accounts, and add the pairs to a DiGraph as edges.
reply_edges = (
replies.groupby(["author", "original_author"]).size().reset_index(name="weight")
)
reply_g = nx.DiGraph()
reply_g.add_weighted_edges_from(reply_edges.itertuples(index=False, name=None))
print(reply_g.number_of_nodes(), reply_g.number_of_edges())
The reply network has 7 nodes and 5 edges. The weight of an edge is the number of replies from one account to the other. Here every weight is 1.
A repost network is built in the same way, from the field that holds the ID of the reposted post.
print(dict(reply_g.in_degree()))
print(dict(reply_g.out_degree()))
The in-degree of an account is the number of accounts that replied to it.
carol has the in-degree 2.
alice, erin, and grace have the in-degree 1, and the other three accounts have 0.
The out-degree of an account is the number of accounts that it replied to.
nx.draw draws a directed network with arrows.
plt.figure(figsize=(6, 5))
nx.draw(
reply_g,
pos=nx.circular_layout(reply_g),
with_labels=True,
node_color="#9ecae1",
node_size=1800,
font_size=11,
edge_color="#888888",
arrowsize=20,
)
plt.margins(0.1)
plt.show()
Each arrow points from the account that replies to the author of the original post.
Two arrows point to carol.
heidi used no hashtag, wrote no reply, and got no reply.
She is in none of the networks, because each network was built from a list of edges.
When the analysis needs every account, add the missing accounts as nodes.
add_nodes_from does not change a node that is already in the network, and add_node adds one node.
all_accounts_g = reply_g.copy()
all_accounts_g.add_nodes_from(posts.author.unique())
print("heidi" in reply_g, "heidi" in all_accounts_g)
print(all_accounts_g.number_of_nodes(), all_accounts_g.number_of_edges())
The copy has 8 nodes and 5 edges.
heidi is a node with no edge in it.
Connected components¶
A network is connected when there is a path between every pair of nodes. A network built from posts is usually not connected. A connected component is a group of nodes with a path between every pair of them, and with no edge to a node outside the group.
This section uses the projection onto the accounts.
nx.is_connected(account_g)
The call returns False.
Some functions need a connected network.
nx.average_shortest_path_length raises an error, because two accounts in different components have no path between them.
try:
nx.average_shortest_path_length(account_g)
except nx.NetworkXError as error:
print(error)
The cell prints Graph is not connected.
nx.connected_components returns each component as a set of nodes.
print(nx.number_connected_components(account_g))
components = sorted(nx.connected_components(account_g), key=len, reverse=True)
print([sorted(c) for c in components])
The network has 2 components.
One has the four accounts alice, bob, carol, and dave.
The other has the three accounts erin, frank, and grace.
A common step is to keep only the largest component.
subgraph returns a view of the network with only the given nodes, and .copy() makes it a new network.
largest = max(nx.connected_components(account_g), key=len)
largest_g = account_g.subgraph(largest).copy()
print(largest_g.number_of_nodes(), largest_g.number_of_edges())
print(nx.average_shortest_path_length(largest_g))
The largest component has 4 nodes and 4 edges. Its average shortest path length is 1.33. When you report a result for the largest component, also report how many nodes of the network it holds.
nx.connected_components does not accept a directed network.
For a directed network, nx.weakly_connected_components finds the components without the direction of the edges.
[sorted(c) for c in nx.weakly_connected_components(reply_g)]
The reply network has the same two groups: alice, bob, carol, and dave, and erin, frank, and grace.
Save the network¶
Save a network to a file to use it in another tool.
nx.write_gexf writes a GEXF file.
The file holds the nodes, the edges, the node attributes, and the edge weights.
Gephi is a desktop application that draws and explores networks, and it opens GEXF files.
See the Gephi quick start for the first steps.
A CSV edge list is a simpler format that most tools read.
nx.to_pandas_edgelist returns the edges as a table, and to_csv writes the table.
The next cell writes both files for the user-hashtag network, into the folder data/ next to this notebook.
data_dir = pathlib.Path("data")
data_dir.mkdir(exist_ok=True)
nx.write_gexf(user_hashtag_g, data_dir / "user-hashtag-network.gexf")
nx.to_pandas_edgelist(user_hashtag_g).to_csv(
data_dir / "user-hashtag-network.csv", index=False
)
The CSV file has one line for each of the 13 edges, after the header line. Its first four lines:
source,target,weight
alice,#dataviz,1
alice,#networks,1
alice,#python,2
The GEXF file also holds the attribute bipartite of each node.
nx.read_gexf reads a GEXF file into NetworkX.
A GEXF file says if the network is directed. A CSV edge list does not, so state it when you share the file.
In Colab, open the file panel on the left to find the folder data and to download the two files.