与其他数据格式相互转换#

转换为 NetworkX 图#

用于将 NetworkX 图与其他格式相互转换的函数。

将数据转换为 NetworkX 图的首选方法是使用图构造器。构造器会调用 to_networkx_graph() 函数,该函数会尝试猜测输入类型并自动进行转换。

示例#

从字典的字典创建具有单条边的图

>>> d = {0: {1: 1}}  # dict-of-dicts single edge (0,1)
>>> G = nx.Graph(d)

另请参阅#

nx_agraph, nx_pydot

to_networkx_graph(data[, create_using, ...])

从已知数据结构创建 NetworkX 图。

字典#

to_dict_of_dicts(G[, nodelist, edge_data])

将图的邻接表示形式作为字典的字典返回。

from_dict_of_dicts(d[, create_using, ...])

从字典的字典返回一个图。

列表#

to_dict_of_lists(G[, nodelist])

将图的邻接表示形式作为字典的列表返回。

from_dict_of_lists(d[, create_using])

从字典的列表返回一个图。

to_edgelist(G[, nodelist])

返回图中的边列表。

from_edgelist(edgelist[, create_using])

从边列表返回一个图。

Numpy#

用于将 NetworkX 图与其他常见数据容器(如 numpy 数组、scipy 稀疏数组和 pandas DataFrame)相互转换的函数。

将数据转换为 NetworkX 图的首选方法是使用图构造器。构造器会调用 to_networkx_graph 函数,该函数会尝试猜测输入类型并自动进行转换。

示例#

从 numpy 数组创建一个 10 节点的随机图

>>> import numpy as np
>>> rng = np.random.default_rng()
>>> a = rng.integers(low=0, high=2, size=(10, 10))
>>> DG = nx.from_numpy_array(a, create_using=nx.DiGraph)

或等价地

>>> DG = nx.DiGraph(a)

该方法会根据 a 的类型在内部调用 from_numpy_array

另请参阅#

nx_agraph, nx_pydot

to_numpy_array(G[, nodelist, dtype, order, ...])

将图的邻接矩阵作为 NumPy 数组返回。

from_numpy_array(A[, parallel_edges, ...])

从二维 NumPy 数组返回一个图。

Scipy#

to_scipy_sparse_array(G[, nodelist, dtype, ...])

将图的邻接矩阵作为 SciPy 稀疏数组返回。

from_scipy_sparse_array(A[, parallel_edges, ...])

从作为 SciPy 稀疏数组给出的邻接矩阵创建一个新图。

Pandas#

to_pandas_adjacency(G[, nodelist, dtype, ...])

将图的邻接矩阵作为 Pandas DataFrame 返回。

from_pandas_adjacency(df[, create_using])

从 Pandas DataFrame 返回一个图。

to_pandas_edgelist(G[, source, target, ...])

将图的边列表作为 Pandas DataFrame 返回。

from_pandas_edgelist(df[, source, target, ...])

从包含边列表的 Pandas DataFrame 返回一个图。