or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

algorithms.mdconversion.mddrawing.mdgenerators.mdgraph-classes.mdgraph-io.mdindex.mdlinear-algebra.md

conversion.mddocs/

0

# Graph Conversion

1

2

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.

3

4

## Capabilities

5

6

### Core Conversion Functions

7

8

Basic conversion functions for common data structures.

9

10

```python { .api }

11

def to_networkx_graph(data, create_using=None, multigraph_input=False):

12

"""

13

Convert various data formats to NetworkX graph.

14

15

Parameters:

16

- data: Input data (edge list, dict of dicts, adjacency matrix, etc.)

17

- create_using: Graph constructor to use (default: Graph)

18

- multigraph_input: If True, expect multigraph input format

19

20

Returns:

21

NetworkX graph created from input data

22

"""

23

24

def from_dict_of_dicts(d, create_using=None, multigraph_input=False):

25

"""Create graph from dictionary of dictionaries format."""

26

27

def to_dict_of_dicts(G, nodelist=None, edge_data=None):

28

"""Convert graph to dictionary of dictionaries format."""

29

30

def from_dict_of_lists(d, create_using=None):

31

"""Create graph from dictionary of lists format."""

32

33

def to_dict_of_lists(G, nodelist=None):

34

"""Convert graph to dictionary of lists format."""

35

36

def from_edgelist(edgelist, create_using=None):

37

"""Create graph from edge list."""

38

39

def to_edgelist(G, nodelist=None):

40

"""Convert graph to edge list."""

41

```

42

43

### NumPy Array Conversion

44

45

Convert between NetworkX graphs and NumPy arrays/matrices.

46

47

```python { .api }

48

def to_numpy_array(G, nodelist=None, dtype=None, order=None, multigraph_weight=sum, weight='weight', nonedge=0.0):

49

"""

50

Convert graph to NumPy adjacency array.

51

52

Parameters:

53

- G: NetworkX graph

54

- nodelist: List of nodes in desired order

55

- dtype: NumPy data type for array

56

- order: Array layout ('C' or 'F')

57

- multigraph_weight: How to handle multiple edges

58

- weight: Edge data key for weights

59

- nonedge: Value for non-edges

60

61

Returns:

62

NumPy array representing graph adjacency matrix

63

"""

64

65

def from_numpy_array(A, parallel_edges=False, create_using=None):

66

"""Create graph from NumPy adjacency array."""

67

68

def to_numpy_matrix(G, nodelist=None, dtype=None, order=None, multigraph_weight=sum, weight='weight', nonedge=0.0):

69

"""Convert graph to NumPy adjacency matrix (deprecated)."""

70

71

def from_numpy_matrix(A, parallel_edges=False, create_using=None):

72

"""Create graph from NumPy adjacency matrix (deprecated)."""

73

74

def to_numpy_recarray(G, nodelist=None, dtype=None, order=None):

75

"""Convert graph to NumPy record array of edges."""

76

```

77

78

### SciPy Sparse Matrix Conversion

79

80

Interface with SciPy sparse matrices for memory-efficient large graph storage.

81

82

```python { .api }

83

def to_scipy_sparse_array(G, nodelist=None, dtype=None, weight='weight', format='csr'):

84

"""

85

Convert graph to SciPy sparse array.

86

87

Parameters:

88

- G: NetworkX graph

89

- nodelist: List of nodes in desired order

90

- dtype: Data type for array elements

91

- weight: Edge data key for weights

92

- format: Sparse array format ('csr', 'csc', 'coo', etc.)

93

94

Returns:

95

SciPy sparse array representing adjacency matrix

96

"""

97

98

def from_scipy_sparse_array(A, parallel_edges=False, create_using=None, edge_attribute='weight'):

99

"""Create graph from SciPy sparse array."""

100

101

def to_scipy_sparse_matrix(G, nodelist=None, dtype=None, weight='weight', format='csr'):

102

"""Convert graph to SciPy sparse matrix."""

103

104

def from_scipy_sparse_matrix(A, parallel_edges=False, create_using=None, edge_attribute='weight'):

105

"""Create graph from SciPy sparse matrix."""

106

```

107

108

### Pandas DataFrame Conversion

109

110

Integration with pandas for data analysis workflows.

111

112

```python { .api }

113

def to_pandas_adjacency(G, nodelist=None, dtype=None, order=None, multigraph_weight=sum, weight='weight', nonedge=0.0):

114

"""

115

Convert graph to pandas adjacency DataFrame.

116

117

Parameters:

118

- G: NetworkX graph

119

- nodelist: List of nodes for rows/columns

120

- dtype: DataFrame data type

121

- order: Not used (kept for compatibility)

122

- multigraph_weight: How to handle multiple edges

123

- weight: Edge data key for weights

124

- nonedge: Value for non-adjacent nodes

125

126

Returns:

127

pandas DataFrame with nodes as index/columns

128

"""

129

130

def from_pandas_adjacency(df, create_using=None):

131

"""Create graph from pandas adjacency DataFrame."""

132

133

def to_pandas_edgelist(G, source='source', target='target', nodelist=None, dtype=None, order=None, edge_key=None):

134

"""Convert graph to pandas edge list DataFrame."""

135

136

def from_pandas_edgelist(df, source='source', target='target', edge_attr=None, create_using=None, edge_key=None):

137

"""Create graph from pandas edge list DataFrame."""

138

```

139

140

### Node and Edge Relabeling

141

142

Functions to relabel nodes for consistency with other data structures.

143

144

```python { .api }

145

def relabel_nodes(G, mapping, copy=True):

146

"""

147

Relabel graph nodes according to mapping.

148

149

Parameters:

150

- G: NetworkX graph

151

- mapping: Dictionary mapping old labels to new labels

152

- copy: If True, return relabeled copy; if False, relabel in-place

153

154

Returns:

155

Graph with relabeled nodes

156

"""

157

158

def convert_node_labels_to_integers(G, first_label=0, ordering='default', label_attribute=None):

159

"""Convert node labels to integers."""

160

```

161

162

## Usage Examples

163

164

### Basic Conversions

165

166

```python

167

import networkx as nx

168

import numpy as np

169

170

# Create sample graph

171

G = nx.Graph()

172

G.add_weighted_edges_from([(1, 2, 0.5), (2, 3, 1.0), (3, 1, 1.5)])

173

174

# Convert to different formats

175

edge_list = nx.to_edgelist(G)

176

dict_of_dicts = nx.to_dict_of_dicts(G)

177

dict_of_lists = nx.to_dict_of_lists(G)

178

179

print("Edge list:", edge_list)

180

print("Dict of dicts:", dict_of_dicts)

181

print("Dict of lists:", dict_of_lists)

182

183

# Convert back to graphs

184

G1 = nx.from_edgelist(edge_list)

185

G2 = nx.from_dict_of_dicts(dict_of_dicts)

186

G3 = nx.from_dict_of_lists(dict_of_lists)

187

```

188

189

### NumPy Array Integration

190

191

```python

192

import networkx as nx

193

import numpy as np

194

195

# Create graph

196

G = nx.complete_graph(4)

197

198

# Convert to NumPy array

199

A = nx.to_numpy_array(G)

200

print("Adjacency matrix:")

201

print(A)

202

203

# Add weights and convert

204

for (u, v) in G.edges():

205

G[u][v]['weight'] = np.random.random()

206

207

A_weighted = nx.to_numpy_array(G, weight='weight')

208

print("Weighted adjacency matrix:")

209

print(A_weighted)

210

211

# Convert back to graph

212

G_from_array = nx.from_numpy_array(A_weighted)

213

print(f"Reconstructed graph: {G_from_array.number_of_nodes()} nodes, {G_from_array.number_of_edges()} edges")

214

```

215

216

### Pandas Integration

217

218

```python

219

import networkx as nx

220

import pandas as pd

221

222

# Create sample graph with attributes

223

G = nx.Graph()

224

G.add_node(1, name='Alice', age=25)

225

G.add_node(2, name='Bob', age=30)

226

G.add_node(3, name='Charlie', age=35)

227

G.add_weighted_edges_from([(1, 2, 0.8), (2, 3, 0.6), (1, 3, 0.4)])

228

229

# Convert to pandas adjacency DataFrame

230

adj_df = nx.to_pandas_adjacency(G, weight='weight')

231

print("Adjacency DataFrame:")

232

print(adj_df)

233

234

# Convert to edge list DataFrame

235

edge_df = nx.to_pandas_edgelist(G)

236

print("Edge list DataFrame:")

237

print(edge_df)

238

239

# Create graph from pandas DataFrame

240

edge_data = pd.DataFrame({

241

'source': [1, 2, 3, 4],

242

'target': [2, 3, 4, 1],

243

'weight': [0.5, 1.0, 1.5, 0.8],

244

'type': ['friend', 'colleague', 'family', 'friend']

245

})

246

247

G_from_df = nx.from_pandas_edgelist(edge_data, edge_attr=True)

248

print(f"Graph from DataFrame: {G_from_df.number_of_nodes()} nodes, {G_from_df.number_of_edges()} edges")

249

print("Edge attributes:", G_from_df[1][2])

250

```

251

252

### SciPy Sparse Matrix Integration

253

254

```python

255

import networkx as nx

256

from scipy import sparse

257

import numpy as np

258

259

# Create large sparse graph

260

G = nx.erdos_renyi_graph(1000, 0.01, seed=42)

261

262

# Convert to sparse matrix (memory efficient)

263

sparse_matrix = nx.to_scipy_sparse_array(G, format='csr')

264

print(f"Sparse matrix shape: {sparse_matrix.shape}")

265

print(f"Non-zero elements: {sparse_matrix.nnz}")

266

print(f"Sparsity: {1 - sparse_matrix.nnz / (sparse_matrix.shape[0] * sparse_matrix.shape[1]):.4f}")

267

268

# Convert back to graph

269

G_from_sparse = nx.from_scipy_sparse_array(sparse_matrix)

270

print(f"Reconstructed graph: {G_from_sparse.number_of_nodes()} nodes, {G_from_sparse.number_of_edges()} edges")

271

272

# Verify graphs are equivalent

273

print(f"Graphs are isomorphic: {nx.is_isomorphic(G, G_from_sparse)}")

274

```

275

276

### Node Relabeling

277

278

```python

279

import networkx as nx

280

import string

281

282

# Create graph with string labels

283

G = nx.Graph()

284

G.add_edges_from([('Alice', 'Bob'), ('Bob', 'Charlie'), ('Charlie', 'Alice')])

285

286

# Relabel to integers

287

mapping = {name: i for i, name in enumerate(G.nodes())}

288

G_int = nx.relabel_nodes(G, mapping)

289

print(f"Original nodes: {list(G.nodes())}")

290

print(f"Relabeled nodes: {list(G_int.nodes())}")

291

292

# Convert node labels to integers automatically

293

G_auto = nx.convert_node_labels_to_integers(G, label_attribute='original_name')

294

print(f"Auto-relabeled nodes: {list(G_auto.nodes())}")

295

print(f"Original names stored as: {nx.get_node_attributes(G_auto, 'original_name')}")

296

297

# Relabel with custom mapping

298

letters = {i: letter for i, letter in enumerate(string.ascii_lowercase)}

299

G_letters = nx.relabel_nodes(G_int, letters)

300

print(f"Letter labels: {list(G_letters.nodes())}")

301

```

302

303

### Working with Different Data Formats

304

305

```python

306

import networkx as nx

307

308

# Dictionary of dictionaries format (adjacency representation)

309

data_dict = {

310

'A': {'B': {'weight': 1}, 'C': {'weight': 2}},

311

'B': {'A': {'weight': 1}, 'D': {'weight': 3}},

312

'C': {'A': {'weight': 2}, 'D': {'weight': 1}},

313

'D': {'B': {'weight': 3}, 'C': {'weight': 1}}

314

}

315

316

# Dictionary of lists format (neighbor lists)

317

data_lists = {

318

'A': ['B', 'C'],

319

'B': ['A', 'D'],

320

'C': ['A', 'D'],

321

'D': ['B', 'C']

322

}

323

324

# Edge list format

325

data_edges = [('A', 'B'), ('A', 'C'), ('B', 'D'), ('C', 'D')]

326

327

# Create graphs from different formats

328

G1 = nx.from_dict_of_dicts(data_dict)

329

G2 = nx.from_dict_of_lists(data_lists)

330

G3 = nx.from_edgelist(data_edges)

331

332

print(f"Graph from dict of dicts: {G1.number_of_edges()} edges")

333

print(f"Graph from dict of lists: {G2.number_of_edges()} edges")

334

print(f"Graph from edge list: {G3.number_of_edges()} edges")

335

336

# Check if weighted edges were preserved

337

print(f"G1 edge weights: {[(u, v, d.get('weight', 1)) for u, v, d in G1.edges(data=True)]}")

338

```