15

In the python library networkx I would like to remove the nodes and edges of a graph which have some property. For example, suppose I wanted to remove all nodes and edges where the degree of a node was < 2. Consider the following psuedocode:

vdict = g.degree_dict()         #dictionary of nodes and their degrees
g.remove_from_nodes(v in g s.t. vdict[v] < 2)

I have seen some syntax that uses set theory notation but as I am still new to python I do not know how to use it. How do I convert this into working python code?

4

4 回答 4

25

Graph.remove_nodes_from() 方法采用节点列表(实际上是容器)。所以你只需要创建一个满足你条件的列表。您可以使用 Python 的列表理解结构紧凑地创建要删除的节点列表。

In [1]: import networkx as nx

In [2]: G = nx.Graph()

In [3]: G.add_edge(1,2)

In [4]: G.add_edge(1,3)

In [5]: G.add_edge(1,4)

In [6]: G.add_edge(2,3)

In [7]: G.add_edge(2,4)

In [8]: G.degree()
Out[8]: {1: 3, 2: 3, 3: 2, 4: 2}

In [9]: remove = [node for node,degree in dict(G.degree()).items() if degree > 2]

In [10]: remove
Out[10]: [1, 2]

In [11]: G.nodes()
Out[11]: [1, 2, 3, 4]

In [12]: G.remove_nodes_from(remove)

In [13]: G.nodes()
Out[13]: [3, 4]
于 2013-08-16T13:16:53.060 回答
7

如果我们有一个初始化图g,则以下将设置fg受到每个顶点的度数必须 > 0 的约束。我们可以很容易地用一个变量来概括 0:

f = nx.Graph()                                                                                                                                     
fedges = filter(lambda x: g.degree()[x[0]] > 0 and g.degree()[x[1]] > 0, g.edges())
f.add_edges_from(fedges)
于 2013-08-17T17:10:56.873 回答
4

请注意,在 Aric 的 networkx==2.2 中,您需要包装G.degree()在字典中,因为 networkx 视图对象没有 items 方法。这条线将是:

[node for node,degree in dict(G.degree()).items() if degree > 2]
于 2019-02-27T17:34:34.857 回答
2

从 networkx==2.6 开始,您可以将其用于 graph G

remove = [node for node, degree in G.degree() if degree < 2]
G.remove_nodes_from(remove)
于 2022-01-01T04:20:17.940 回答