Skip to content
Advertisement

Pandas union with parent ids in the same dataframe

I have a pandas dataframe that looks like this:

JavaScript

I want to return the folder structure for each line in a separate colunm, for example

  • line 1: A is the root there is no parent all ids are 0 = A
  • line 2: B is under A, id = 1, so the path is A/B
  • line 3: C is under id A=1 for level0 and under B=2 for level1, resulting = A/B/C
  • line 4: D is under id A=1 for level0 and under B=2 for level1, resulting = A/B/D
  • line 5: E is under id A=1 for level0 and under B=2 for level1 and under D=4 for level 2, resulting = A/B/D/E

and this go on and on, I can have multiple Roots meaning level0 = 0 and if level 0 is not 0 means that is not Root so it’s related to a Root …(obvious i think )

How can I do this with Pandas?

Advertisement

Answer

One approach with melt

JavaScript

Output

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement