Converting to and from other data formats#

To NetworkX Graph#

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

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

Examples#

通过字典的字典创建一个包含单条边的图

>>> d = {0: {1: 1}}  # 字典的字典,包含单条边 (0,1)
>>> G = nx.Graph(d)

See Also#

nx_agraph, nx_pydot

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

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

Dictionaries#

to_dict_of_dicts(G[, nodelist, edge_data])

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

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

返回一个从字典的字典中创建的图。

Lists#

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 函数,该函数会尝试猜测输入类型并自动进行转换。

Examples#

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

`python 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) `

或者等效地:

`python DG = nx.DiGraph(a) `

这会在内部根据 a 的类型调用 from_numpy_array

See Also#

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返回一个图。