Python package for creating and manipulating graphs and networks
—
Functions to convert between NetworkX graphs and other data structures including matrices, pandas DataFrames, dictionaries, edge lists, and external graph libraries. These functions enable seamless integration with the broader Python scientific ecosystem.
Basic conversion functions for common data structures.
def to_networkx_graph(data, create_using=None, multigraph_input=False):
"""
Convert various data formats to NetworkX graph.
Parameters:
- data: Input data (edge list, dict of dicts, adjacency matrix, etc.)
- create_using: Graph constructor to use (default: Graph)
- multigraph_input: If True, expect multigraph input format
Returns:
NetworkX graph created from input data
"""
def from_dict_of_dicts(d, create_using=None, multigraph_input=False):
"""Create graph from dictionary of dictionaries format."""
def to_dict_of_dicts(G, nodelist=None, edge_data=None):
"""Convert graph to dictionary of dictionaries format."""
def from_dict_of_lists(d, create_using=None):
"""Create graph from dictionary of lists format."""
def to_dict_of_lists(G, nodelist=None):
"""Convert graph to dictionary of lists format."""
def from_edgelist(edgelist, create_using=None):
"""Create graph from edge list."""
def to_edgelist(G, nodelist=None):
"""Convert graph to edge list."""Convert between NetworkX graphs and NumPy arrays/matrices.
def to_numpy_array(G, nodelist=None, dtype=None, order=None, multigraph_weight=sum, weight='weight', nonedge=0.0):
"""
Convert graph to NumPy adjacency array.
Parameters:
- G: NetworkX graph
- nodelist: List of nodes in desired order
- dtype: NumPy data type for array
- order: Array layout ('C' or 'F')
- multigraph_weight: How to handle multiple edges
- weight: Edge data key for weights
- nonedge: Value for non-edges
Returns:
NumPy array representing graph adjacency matrix
"""
def from_numpy_array(A, parallel_edges=False, create_using=None):
"""Create graph from NumPy adjacency array."""
def to_numpy_matrix(G, nodelist=None, dtype=None, order=None, multigraph_weight=sum, weight='weight', nonedge=0.0):
"""Convert graph to NumPy adjacency matrix (deprecated)."""
def from_numpy_matrix(A, parallel_edges=False, create_using=None):
"""Create graph from NumPy adjacency matrix (deprecated)."""
def to_numpy_recarray(G, nodelist=None, dtype=None, order=None):
"""Convert graph to NumPy record array of edges."""Interface with SciPy sparse matrices for memory-efficient large graph storage.
def to_scipy_sparse_array(G, nodelist=None, dtype=None, weight='weight', format='csr'):
"""
Convert graph to SciPy sparse array.
Parameters:
- G: NetworkX graph
- nodelist: List of nodes in desired order
- dtype: Data type for array elements
- weight: Edge data key for weights
- format: Sparse array format ('csr', 'csc', 'coo', etc.)
Returns:
SciPy sparse array representing adjacency matrix
"""
def from_scipy_sparse_array(A, parallel_edges=False, create_using=None, edge_attribute='weight'):
"""Create graph from SciPy sparse array."""
def to_scipy_sparse_matrix(G, nodelist=None, dtype=None, weight='weight', format='csr'):
"""Convert graph to SciPy sparse matrix."""
def from_scipy_sparse_matrix(A, parallel_edges=False, create_using=None, edge_attribute='weight'):
"""Create graph from SciPy sparse matrix."""Integration with pandas for data analysis workflows.
def to_pandas_adjacency(G, nodelist=None, dtype=None, order=None, multigraph_weight=sum, weight='weight', nonedge=0.0):
"""
Convert graph to pandas adjacency DataFrame.
Parameters:
- G: NetworkX graph
- nodelist: List of nodes for rows/columns
- dtype: DataFrame data type
- order: Not used (kept for compatibility)
- multigraph_weight: How to handle multiple edges
- weight: Edge data key for weights
- nonedge: Value for non-adjacent nodes
Returns:
pandas DataFrame with nodes as index/columns
"""
def from_pandas_adjacency(df, create_using=None):
"""Create graph from pandas adjacency DataFrame."""
def to_pandas_edgelist(G, source='source', target='target', nodelist=None, dtype=None, order=None, edge_key=None):
"""Convert graph to pandas edge list DataFrame."""
def from_pandas_edgelist(df, source='source', target='target', edge_attr=None, create_using=None, edge_key=None):
"""Create graph from pandas edge list DataFrame."""Functions to relabel nodes for consistency with other data structures.
def relabel_nodes(G, mapping, copy=True):
"""
Relabel graph nodes according to mapping.
Parameters:
- G: NetworkX graph
- mapping: Dictionary mapping old labels to new labels
- copy: If True, return relabeled copy; if False, relabel in-place
Returns:
Graph with relabeled nodes
"""
def convert_node_labels_to_integers(G, first_label=0, ordering='default', label_attribute=None):
"""Convert node labels to integers."""import networkx as nx
import numpy as np
# Create sample graph
G = nx.Graph()
G.add_weighted_edges_from([(1, 2, 0.5), (2, 3, 1.0), (3, 1, 1.5)])
# Convert to different formats
edge_list = nx.to_edgelist(G)
dict_of_dicts = nx.to_dict_of_dicts(G)
dict_of_lists = nx.to_dict_of_lists(G)
print("Edge list:", edge_list)
print("Dict of dicts:", dict_of_dicts)
print("Dict of lists:", dict_of_lists)
# Convert back to graphs
G1 = nx.from_edgelist(edge_list)
G2 = nx.from_dict_of_dicts(dict_of_dicts)
G3 = nx.from_dict_of_lists(dict_of_lists)import networkx as nx
import numpy as np
# Create graph
G = nx.complete_graph(4)
# Convert to NumPy array
A = nx.to_numpy_array(G)
print("Adjacency matrix:")
print(A)
# Add weights and convert
for (u, v) in G.edges():
G[u][v]['weight'] = np.random.random()
A_weighted = nx.to_numpy_array(G, weight='weight')
print("Weighted adjacency matrix:")
print(A_weighted)
# Convert back to graph
G_from_array = nx.from_numpy_array(A_weighted)
print(f"Reconstructed graph: {G_from_array.number_of_nodes()} nodes, {G_from_array.number_of_edges()} edges")import networkx as nx
import pandas as pd
# Create sample graph with attributes
G = nx.Graph()
G.add_node(1, name='Alice', age=25)
G.add_node(2, name='Bob', age=30)
G.add_node(3, name='Charlie', age=35)
G.add_weighted_edges_from([(1, 2, 0.8), (2, 3, 0.6), (1, 3, 0.4)])
# Convert to pandas adjacency DataFrame
adj_df = nx.to_pandas_adjacency(G, weight='weight')
print("Adjacency DataFrame:")
print(adj_df)
# Convert to edge list DataFrame
edge_df = nx.to_pandas_edgelist(G)
print("Edge list DataFrame:")
print(edge_df)
# Create graph from pandas DataFrame
edge_data = pd.DataFrame({
'source': [1, 2, 3, 4],
'target': [2, 3, 4, 1],
'weight': [0.5, 1.0, 1.5, 0.8],
'type': ['friend', 'colleague', 'family', 'friend']
})
G_from_df = nx.from_pandas_edgelist(edge_data, edge_attr=True)
print(f"Graph from DataFrame: {G_from_df.number_of_nodes()} nodes, {G_from_df.number_of_edges()} edges")
print("Edge attributes:", G_from_df[1][2])import networkx as nx
from scipy import sparse
import numpy as np
# Create large sparse graph
G = nx.erdos_renyi_graph(1000, 0.01, seed=42)
# Convert to sparse matrix (memory efficient)
sparse_matrix = nx.to_scipy_sparse_array(G, format='csr')
print(f"Sparse matrix shape: {sparse_matrix.shape}")
print(f"Non-zero elements: {sparse_matrix.nnz}")
print(f"Sparsity: {1 - sparse_matrix.nnz / (sparse_matrix.shape[0] * sparse_matrix.shape[1]):.4f}")
# Convert back to graph
G_from_sparse = nx.from_scipy_sparse_array(sparse_matrix)
print(f"Reconstructed graph: {G_from_sparse.number_of_nodes()} nodes, {G_from_sparse.number_of_edges()} edges")
# Verify graphs are equivalent
print(f"Graphs are isomorphic: {nx.is_isomorphic(G, G_from_sparse)}")import networkx as nx
import string
# Create graph with string labels
G = nx.Graph()
G.add_edges_from([('Alice', 'Bob'), ('Bob', 'Charlie'), ('Charlie', 'Alice')])
# Relabel to integers
mapping = {name: i for i, name in enumerate(G.nodes())}
G_int = nx.relabel_nodes(G, mapping)
print(f"Original nodes: {list(G.nodes())}")
print(f"Relabeled nodes: {list(G_int.nodes())}")
# Convert node labels to integers automatically
G_auto = nx.convert_node_labels_to_integers(G, label_attribute='original_name')
print(f"Auto-relabeled nodes: {list(G_auto.nodes())}")
print(f"Original names stored as: {nx.get_node_attributes(G_auto, 'original_name')}")
# Relabel with custom mapping
letters = {i: letter for i, letter in enumerate(string.ascii_lowercase)}
G_letters = nx.relabel_nodes(G_int, letters)
print(f"Letter labels: {list(G_letters.nodes())}")import networkx as nx
# Dictionary of dictionaries format (adjacency representation)
data_dict = {
'A': {'B': {'weight': 1}, 'C': {'weight': 2}},
'B': {'A': {'weight': 1}, 'D': {'weight': 3}},
'C': {'A': {'weight': 2}, 'D': {'weight': 1}},
'D': {'B': {'weight': 3}, 'C': {'weight': 1}}
}
# Dictionary of lists format (neighbor lists)
data_lists = {
'A': ['B', 'C'],
'B': ['A', 'D'],
'C': ['A', 'D'],
'D': ['B', 'C']
}
# Edge list format
data_edges = [('A', 'B'), ('A', 'C'), ('B', 'D'), ('C', 'D')]
# Create graphs from different formats
G1 = nx.from_dict_of_dicts(data_dict)
G2 = nx.from_dict_of_lists(data_lists)
G3 = nx.from_edgelist(data_edges)
print(f"Graph from dict of dicts: {G1.number_of_edges()} edges")
print(f"Graph from dict of lists: {G2.number_of_edges()} edges")
print(f"Graph from edge list: {G3.number_of_edges()} edges")
# Check if weighted edges were preserved
print(f"G1 edge weights: {[(u, v, d.get('weight', 1)) for u, v, d in G1.edges(data=True)]}")Install with Tessl CLI
npx tessl i tessl/pypi-networkx