How can I get branch of a networkx graph from pandas dataframe in Python in the form of a new pandas dataframe?
You are already using networkx, why not ask it to get the paths for you:
import networkx as nx
# create a digraph from your edges
G = nx.from_pandas_edgelist( df, 'From', 'To', create_using=nx.DiGraph())
root_node = 'Node1'
leaf_nodes = df.To[~(df.To.isin(df.From))]
# get all paths from leaf_nodes back to root_node
paths = []
for node in leaf_nodes:
paths.append( nx.shortest_path(G, root_node, node) )
result = pd.DataFrame(paths)
result:
0 1 2 3
0 Node1 Node2 Node4 Node8
1 Node1 Node2 Node5 Node9
2 Node1 Node3 Node6 Node10
3 Node1 Node3 Node7 Node11