I have a table with 2 ID fields like this, where it is possible for a parent to be linked to itself:
| Child | Parent |
|---|---|
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 3 |
I created a digraph using networkx and am now trying to write a function to identify all the roots and leaves for each row and adding them back to the original dataframe:
def find_leaves(G, node):
d = list(nx.descendants(G, node))+[node]
H = G.subgraph(d)
return [a for a in H.nodes if H.out_degree(a)==0 | (H.out_degree(a)==1 and <checking whether the node is a self-loop>)]
def find_roots(G, node):
d = list(nx.ancestors(G, node))+[node]
H = G.subgraph(d)
return [a for a in H.nodes if H.in_degree(a)==0 | (H.in_degree(a)==1 and <checking whether the node is a self-loop>)]
Because a parent/child can be linked to itself, I'm looking to add a second clause to check whether the out/in degree = 1 and the node is a self loop. I am fairly new to networkx but from the 2.5 documentation it seems that most functions for self-loop return an entire list of self-looped nodes in the graph e.g. nx.nodes_with_selfloops(G).
Is there a way to check whether a node is self-looped without having to check through the entire list every time?