NetworkX

添加节点

# 添加单个节点
G.add_node(2)
G.add_node('a')
# 添加节点集合
G.add_nodes_from([1,2,3,'a','b','c'])

添加边

# 添加单条边
G.add_edge('a', 'b')
# 添加多条边
G.add_edges_from([('b','c'), ('a','d')])

查询

节点

# 节点数量
G.number_of_nodes()
G.order()
# 输出全部节点
G.nodes()
# 节点'n'是否在G中,若在,则返回True
'n' in G

# 边的数量
G.number_of_edges()
# 输出全部边
G.edges()

# 各个节点的度
nx.degree(G)
# 单个节点的度
nx.degree(G, 'a')
# 度频率
nx.degree_histogram(G)

密度

# 图G的密度[无向]:d=2m/n(n-1) [有向]: d=m/n(n-1)
nx.density(G)

图的信息

nx.info(G)

有向图\(\leftrightarrow\)无向图

# 判断是否是有向图
nx.is_directed(G)
# 返回无向图G的有向图视图
G_2 = nx.to_directed(G)
# 返回有向图G的无向图视图
G_2 = nx.to_undirected(G)

空图

# 图G是否是空图

nx.is_empty(G)

# 返回删除所有边的图G的副本

G_1 = nx.create_empty_copy(G)

邻居节点

# 返回'a'的邻居节点

list(nx.neighbors(G, 'a'))

# 返回'a'的非邻居节点

list(nx.non_neighbors(G, 'a'))

# 共同邻居节点

list(nx.common_neighbors(G, 'a', 'c'))

子图

G_7= nx.subgraph(G_6,['a','b','c'])

# 图G返回由指定边组成的子图

G_10 = nx.path_graph(['a', 'b', 'c', 'd', 'e'])
G_10 = G_10.edge_subgraph([('b','c'),('d','e')])

删点和删边

G_8 = nx.cycle_graph(['a','b','c','d','e']) # 生成一个无环图
G_8 = nx.restricted_view(G_8, ['e'], [('c', 'd'),('a', 'b')])

生成图

barabasi_albert_graph

barabasi_albert_graph(n, m, seed=None, initial_graph=None)

点击查看

Parameters

  • n [int] Number of nodes
  • m [int] Number of edges to attach from a new node to existing nodes
  • seed [integer, random_state, or None (default)] Indicator of random number generation state.

Returns

  • G [Graph]
  • Raises NetworkXError If m does not satisfy 1 <= m < n, or the initial graph number of nodes m0 does not satisfy m <= m0 <= n.

erdos_renyi_graph

erdos_renyi_graph(n, p, seed=None, directed=False)

点击查看

Parameters

  • n [int] The number of nodes.
  • p [float] Probability for edge creation.
  • seed [integer, random_state, or None (default)] Indicator of random number generation state.
  • directed [bool, optional (default=False)] If True, this function returns a directed graph.

其他格式转换(NumPy, List, Pandas)

Lists

to_dict_of_lists(G[, nodelist]) Returns adjacency representation of graph as a dictionary of lists.
from_dict_of_lists(d[, create_using]) Returns a graph from a dictionary of lists.
to_edgelist(G[, nodelist]) Returns a list of edges in the graph.
from_edgelist(edgelist[, create_using]) Returns a graph from a list of edges.

Pandas

to_pandas_edgelist

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

点击查看

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

Parameters

  • G [graph] The NetworkX graph used to construct the Pandas DataFrame.
  • source [str or int, optional] A valid column name (string or integer) for the source nodes (for the directed case).
  • target [str or int, optional] A valid column name (string or integer) for the target nodes (for the directed case).
  • nodelist [list, optional] Use only nodes specified in nodelist dtype [dtype, default None] Use to create the DataFrame. Data type to force. Only a single dtype is allowed. If None, infer.
  • order [None] An unused parameter mistakenly included in the function. Deprecated since version 2.6: This is deprecated and will be removed in NetworkX v3.0.
  • edge_key [str or int or None, optional (default=None)] A valid column name (string or integer) for the edge keys (for the multigraph case). If None, edge keys are not stored in the DataFrame.

Returns

  • df [Pandas DataFrame] Graph edge list

Example

>>> G = nx.Graph(
... 	[
... 		("A", "B", {"cost": 1, "weight": 7}),
... 		("C", "E", {"cost": 9, "weight": 10}),
... 	]
... )
>>> df = nx.to_pandas_edgelist(G, nodelist=["A", "C"])
>>> df[["source", "target", "cost", "weight"]]
	source 	target 	cost 	weight
0 	A 	B 	1 	7
1 	C 	E 	9 	10

from_pandas_edgelist

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

点击查看

Parameters

  • df [Pandas DataFrame] An edge list representation of a graph

  • source [str or int] A valid column name (string or integer) for the source nodes (for the directed case).

  • target [str or int] A valid column name (string or integer) for the target nodes (for the directed case).

  • edge_attr [str or int, iterable, True, or None] A valid column name (str or int) or iterable of column names that are used to retrieve items and add them to the graph as edge attributes. If True, all of the remaining columns will be added. If None, no edge attributes are added to the graph.

  • create_using [NetworkX graph constructor, optional (default=nx.Graph)] Graph type to create. If graph instance, then cleared before populated.

  • edge_key [str or None, optional (default=None)] A valid column name for the edge keys (for a MultiGraph). The values in this column are used for the edge keys when adding edges if create_using is a multigraph.

Example

>>> import pandas as pd
>>> pd.options.display.max_columns = 20
>>> import numpy as np
>>> rng = np.random.RandomState(seed=5)
>>> ints = rng.randint(1, 11, size=(3, 2))
>>> a = ["A", "B", "C"]
>>> b = ["D", "A", "E"]
>>> df = pd.DataFrame(ints, columns=["weight", "cost"])
>>> df[0] = a
>>> df["b"] = b
>>> df[["weight", "cost", 0, "b"]]
	weight 	cost 	0 	b
0 	4 	7 	A 	D
1 	7 	1 	B 	A
2 	10 	9 	C 	E
>>> G = nx.from_pandas_edgelist(df, 0, "b", ["weight", "cost"])
>>> G["E"]["C"]["weight"]
10
>>> G["E"]["C"]["cost"]
9
>>> edges = pd.DataFrame(
... {
... "source": [0, 1, 2],
... "target": [2, 2, 3],
... "weight": [3, 4, 5],
... "color": ["red", "blue", "blue"],
... }
... )
>>> G = nx.from_pandas_edgelist(edges, edge_attr=True)
>>> G[0][2]["color"]
'red'

Basic graph types

Graph.subgraph

Graph.subgraph(nodes)

Returns a SubGraph view of the subgraph induced on nodes.

点击查看

Parameters

  • nodes [list, iterable] A container of nodes which will be iterated through once.

Returns

  • G [SubGraph View] A subgraph view of the graph. The graph structure cannot be changed but
    node/edge attributes can and are shared with the original graph.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> H = G.subgraph([0, 1, 2])
>>> list(H.edges)
[(0, 1), (1, 2)]

Graph.edge_subgraph

Graph.edge_subgraph(edges)

Returns the subgraph induced by the specified edges.

点击查看
**Parameters**

- **edges** [iterable] An iterable of edges in this graph.

**Returns**

- **G** [Graph] An edge-induced subgraph of this graph with the same edge attributes.
posted @ 2022-11-25 12:48  X1OO  阅读(52)  评论(0)    收藏  举报