删除入网度和出网度等于1的networkx DiGraph中的所有节点 [英] Remove all nodes in a networkx DiGraph with in-degree and out-degree equal to 1

查看:1231
本文介绍了删除入网度和出网度等于1的networkx DiGraph中的所有节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在NetworkX中制作了一个DiGraph:

Say I make a DiGraph in NetworkX:

import networkx as nx

G = nx.DiGraph()

n = ["A","B","C","D","E","F","H","I","J","K","L","X","Y","Z"]

e = [("A","Z"),("Z","B"),("B","Y"),("Y","C"),("C","G"),("G","H"),("G","I"),("I","J"),("K","J"),("J","L"),("F","E"),("E","D"),("D","X"),("X","C")]

G.add_nodes_from(n)

G.add_edges_from(e)

我将如何删除入度和出度等于1的所有节点,以使图看起来像这样?

How would I remove all the nodes with a in-degree and an out-degree equal to 1, so that my graph would look like this?:

import networkx as nx

G = nx.DiGraph()

n = ["A","C","F","G","H","J","K","L"]

e = [("A","C"),("C","G"),("G","H"),("G","J"),("K","J"),("J","L")

G.add_nodes_from(n)

G.add_edges_from(e)

该想法是删除直通"节点并保持连接性.

The idea is to remove the "flow-through" nodes and retain connectivity.

推荐答案

尽管我看不到从("A","C")和("G" ,"J").

The following code does what you want although I don't see where you would get edges from ("A", "C") and ("G", "J") in the final result.

import networkx as nx

def remove_edges(g, in_degree=1, out_degree=1):
    g2=g.copy()
    d_in=g2.in_degree(g2)
    d_out=g2.out_degree(g2)
    print(d_in)
    print(d_out)
    for n in g2.nodes():
        if d_in[n]==in_degree and d_out[n] == out_degree: 
            g2.remove_node(n)
    return g2

G_trimmed = remove_edges(G)
G_trimmed.edges()
#outputs [('C', 'G'), ('G', 'H'), ('K', 'J'), ('J', 'L')]
G_trimmed.nodes()
#outputs ['A', 'C', 'G', 'F', 'H', 'K', 'J', 'L']

这篇关于删除入网度和出网度等于1的networkx DiGraph中的所有节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆