Python Louvain Community Detection

0.16 · maintenance · verified Thu Apr 16

python-louvain is a Python implementation of the Louvain algorithm for community detection in large networks. It is built on top of the NetworkX framework. The current stable version is 0.16, released in January 2022. The project appears to be in a maintenance phase, with infrequent releases.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a simple NetworkX graph and then apply the Louvain algorithm using `community_louvain.best_partition` to find community assignments. It also shows how to calculate the modularity of the resulting partition.

import networkx as nx
from community import community_louvain

# Create a sample graph
G = nx.Graph()
G.add_edges_from([(0, 1), (0, 2), (1, 2), (3, 4), (3, 5), (4, 5), (0, 3)])

# Compute the best partition using the Louvain method
partition = community_louvain.best_partition(G)

print("Graph Nodes:", G.nodes())
print("Detected Communities:", partition)

# Example of how to get the modularity of the partition
modularity = community_louvain.modularity(partition, G)
print("Modularity:", modularity)

view raw JSON →