英文:
How to remove nodes by both name and condition for Networkx?
问题
我有一个边缘列表如下。我想删除所有以A或C开头且度数<= 1的节点。
(A2,A1)
(A1,B1)
(B1,C2)
(C2,B2)
(B2,C1)
(B1,A3)
例如,对于上面的列表,我想得到:
(B1,C2)
(C2,B2)
我该怎么做?
英文:
I have an edge list like below. I want to remove all nodes start with A or C, and degree <= 1.
(A2,A1)
(A1,B1)
(B1,C2)
(C2,B2)
(B2,C1)
(B1,A3)
E.g, for the list above, I want to get:
(B1,C2)
(C2,B2)
How can I do it?
答案1
得分: 2
你可以这样做来移除以'A'或'C'开头且度数小于等于1的节点:
import networkx as nx
G = nx.DiGraph()
G.add_edges_from([
("A2", "A1"),
("A1", "B1"),
("B1", "C2"),
("C2", "B2"),
("B2", "C1"),
("B1", "A3"),
])
def node_filter(node):
return (
(node.startswith('A') or
node.startswith('C')) and
G.out_degree(node) <= 1
)
G.remove_nodes_from(list(nx.subgraph_view(G, filter_node=node_filter).nodes))
然而,在你的示例中,节点'C2'将被删除,因为它的出度为1且以'C'开头。因此,边缘(C2, B2)
和(B1, C2)
将被删除。你只剩下节点B1
和B2
。
print(G.edges)
G.remove_nodes_from(list(nx.subgraph_view(G, filter_node=node_filter).nodes))
print(G.edges)
print(G.nodes)
[('A2', 'A1'), ('A1', 'B1'), ('B1', 'C2'), ('B1', 'A3'), ('C2', 'B2'), ('B2', 'C1')]
[]
['B1', 'B2']
英文:
You can do this to remove nodes that start with 'A' or 'C', and have a degree <= 1:
import networkx as nx
G = nx.DiGraph()
G.add_edges_from([
("A2", "A1"),
("A1", "B1"),
("B1", "C2"),
("C2", "B2"),
("B2", "C1"),
("B1", "A3"),
])
def node_filter(node):
return (
(node.startswith('A') or
node.startswith('C')) and
G.out_degree(node) <= 1
)
G.remove_nodes_from(list(nx.subgraph_view(G, filter_node=node_filter).nodes))
However in your example, the node 'C2' will be deleted because it has an out-degree of 1 and begins with C. Therefore, the edge (C2, B2)
and (B1, C2)
will be deleted. You are only left with the nodes B1
and B2
.
print(G.edges)
G.remove_nodes_from(list(nx.subgraph_view(G, filter_node=node_filter).nodes))
print(G.edges)
print(G.nodes)
[('A2', 'A1'), ('A1', 'B1'), ('B1', 'C2'), ('B1', 'A3'), ('C2', 'B2'), ('B2', 'C1')]
[]
['B1', 'B2']
答案2
得分: 0
Credit to @Tom McLean
import networkx as nx
G = nx.Graph()
G.add_edges_from([('A2', 'A1'),
('A1', 'B1'),
('B1', 'C2'),
('C2', 'B2'),
('B2', 'C1'),
('B1', 'A3')])
def node_filter(node):
return(
(node.startswith('A') or
node.startswith('C')) and
G.degree(node) <= 1)
for i in range(0,len(G)):
G.remove_nodes_from(list(nx.subgraph_view(G, filter_node = node_filter).nodes))
i = i+1
print(G.nodes)
print(G.edges)
Will result in
['B1', 'C2', 'B2']
[('B1', 'C2'), ('C2', 'B2')]
英文:
Credit to @Tom McLean
import networkx as nx
G = nx.Graph()
G.add_edges_from([('A2', 'A1'),
('A1', 'B1'),
('B1', 'C2'),
('C2', 'B2'),
('B2', 'C1'),
('B1', 'A3')])
def node_filter(node):
return(
(node.startswith('A') or
node.startswith('C')) and
G.degree(node) <= 1)
for i in range(0,len(G)):
G.remove_nodes_from(list(nx.subgraph_view(G, filter_node = node_filter).nodes))
i = i+1
print(G.nodes)
print(G.edges)
Will result in
['B1', 'C2', 'B2']
[('B1', 'C2'), ('C2', 'B2')]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论