NetworkX is a Python package for working with graphs.
I recently learned how to get other nodes related to a particular node in the NetworkX directed graph DiGraph
, so I'll write it for later.
The assumed effective graph looks like this.
Focusing on node C, B is the parent of C and D is the child of C. Also, A and B are ancestors of C, and D and E are descendants of C.
First, let's import NetworkX and create an empty directional graph.
>>> import networkx as nx
>>> g = nx.DiGraph()
Next, create the graph in the above figure with ʻadd_path`. When you create a path, it seems that you can create a node without explicitly adding it.
>>> g.add_path(["A","B","C","D","E"])
>>> g.nodes()
['E', 'C', 'D', 'A', 'B']
Now, to get the parent and child of C, use the methods predecessors
and successors
of graph g. The result is returned as list
, as there can be multiple parents and children each.
>>> g.predecessors("C")
['B']
>>> g.successors("C")
['D']
On the other hand, to get the ancestors and offspring of C, use the functions descendants
and ʻansstors. The result is returned with
set`.
>>> nx.descendants(g, "C")
{'D', 'E'}
>>> nx.ancestors(g, "C")
{'A', 'B'}
Note that for parents and children, the method returns the result as list
, for ancestors and offspring, the function is used, and the result is returned as set
.
Recommended Posts