问题描述
我正在使用Networkx的k核移除度数小于2的节点。
n=20
G = nx.gnm_random_graph(n=20,m=30,seed=1)
nx.draw(G,with_labels=True)
plt.show()
retain_node_ids = [1,8]
G.add_edges_from([(u,v) for u in retain_node_ids for v in (n,n+1)])
pos = nx.spring_layout(G)
G = nx.k_core(G,k=2)
nx.draw(G,with_labels=True,pos=pos)
plt.show()
k-core返回子图。但是我也想获得使用k-core时删除的节点和边的列表。
任何建议都将非常有用。
解决方法
nx.k_core
仅返回相应的最大子图。为了找到结果子图中未包含的节点和边,您必须找到两个图之间的节点差,然后从中找到边差。使用示例nx.gnm_random_graph
:
diff_nodes = set(G.nodes()).difference(H.nodes())
print(diff_nodes)
# {2,4,11,19}
removed_edges = {e for e in G.edges() for n in diff_nodes if n in e}
print(removed_edges)
# {(2,8),(4,18),(7,11),(13,19)}