0

I am trying to form a parent to child relationship combination using data available in my pandas dataframe.

Data Example:

Parent Child
A B
A C
B D
B C
C D

Expected chain results:

A|B

A|C

A|B|D

A|B|C

A|C|D

A|B|C|D

I tried something with networkx package to trace out the trees. I am partially successful. But it misses some of the hierarchies shown in the expected result.

Like, if the child has sub-nodes associated with it, it's not appearing as separate result.

For example, in the above data B is a child to A and has D & C are childs of B.

While applying my code, it shows A|B|D & A|B|C|D alone.

A|B is skipped as B has childs (C & D )

A|B|C is skipped as B has childs (C & D ) and subsequently C also has child (D)

A|C is skipped as C has child (D)

I used the code shown in below link

How to use recursion to record all routes in a parent child hierarchy?

3
  • "Need help" is not a suitable question here. Please show your attempt, and where things are not going as expected, and what you have done to research and debug. Commented Sep 26, 2023 at 16:26
  • @trincot: I've added whatever I tried Commented Sep 26, 2023 at 16:32
  • This is a network problem, read on networkx as you already tagged. You can think of your data as a (collection of) trees, then find all the leaves, and path to the tree roots. Commented Sep 26, 2023 at 16:45

1 Answer 1

1

A possible solution with all_simple_paths :

G = nx.from_pandas_edgelist(df, # or pd.read_csv("file.csv")
    source="parent", target="child", create_using=nx.DiGraph)

root = next(nx.topological_sort(G))

out = (
    pd.Series(
        [
            list(nx.all_simple_paths(G, root, c)) for c in df["child"]
        ]
    ).explode().sort_values(key=lambda s: s.str.len())
    .drop_duplicates().str.join("|").to_frame("paths")
)

Output :

print(out)

     paths
0      A|B
1      A|C
1    A|B|C
2    A|B|D
2    A|C|D
2  A|B|C|D
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. Thanks for your answer. I am able to get the tree structure as expected now. Once again, thanks for your guidance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.