Transforming from one table to another in Python

Viewed 68

Original Table:

A        B 
-----------
1        2
1        4
2        3
3        5
3        6
2        7
5        100
6        100
7        100
4        100

Table I want to generate:

1     2     3     5     100
1     2     3     6     100
1     2     7    100    NAN
1     4    100   NAN    NAN

Hello! I am trying to create a tree in python out of a dataset that I have (see Original Table). There are relations here - 1 maps to 2 map to 3 maps to 5 maps to 100. (100 signifies the leaf node or the end of a path of the tree and 1 is always the root node- all paths start with 1) I first want to create arrays with complete paths of the tree (see Table I want to get) and I tried this using recursive functions, but it gets really complicated. Any ideas on how I can proceed? Or if there is an inbuilt function to do this transformation from 1st table to 2nd table.

(Main Goal: Getting from 'Original Table' to 'Table I want to generate'

I have attached my code so far here.

import pandas as pd
import numpy as np 

data = {'A':  [1, 1,2,3,3,2,1,6,5,7,4],
        'B': [2,4,3,5,6,7,100,100,100,100]
        }

df = pd.DataFrame (data, columns = ['A','B'])

print (df)

def filt(df,val):
    return df[df.A==val]

c2=1

global vec 
vec = np.array([c2])
def search(c2):
   temp_df= filt(df,c2)
   print(temp_df)
   a=temp_df[temp_df.columns[1]]
   for row in range(temp_df.shape[0]):
   
        if a.iloc[row]!=100:
            global vec 
            vec=np.append(vec,a.iloc[row])
            search(a.iloc[row])
                       
        else:
            vec=np.append(vec,a.iloc[row])
            print(vec)
            vec=vec[:-2]
 

search(c2)
1 Answers

You can use a recursive generator function:

import pandas as pd
t1 = [[1, 2], [1, 4], [2, 3], [3, 5], [3, 6], [2, 7], [5, 100], [6, 100], [7, 100], [4, 100]]
def get_paths(n, c = []):
  if not (v:=[b for a, b in t1 if a == n]):
     yield c + [n]
  else:
     yield from [i for b in v for i in get_paths(b, c+[n])]

m = max(map(len, r:=list(get_paths(1))))
df = pd.DataFrame([i+([None]*(m - len(i))) for i in r])

Output:

   0  1    2     3     4
0  1  2    3     5   100
1  1  2    3     6   100
2  1  2    7   100   NaN
3  1  4  100   NaN   NaN
Related