Home > Mobile >  Read data from a pandas Dataframe and create a tree and represent it as a dictionary
Read data from a pandas Dataframe and create a tree and represent it as a dictionary

Time:11-26

Suppose I have a dataframe

df1 = pd.DataFrame({'parent id': [0,0,2,2,2,2,2,2,3,3,4,4,4], 
                    'id' : [1,2,3,4,11,12,13,16,14,15,41,42,43]})

I want to use this data to create a tree and then represent the tree as a dictionary like this:

tree = {0: [1, {2: [{3: [14, 15]}, {4: [41, 42, 43]}, 11, 12, 13, 16]}]})

How should I do this?

CodePudding user response:

The order in the of the object/numbers in the list isn't exactly like yours, but I'm guessing that doesn't matter.

items = df[~df['id'].isin(df['parent id'])].groupby('parent id').apply(lambda x: {x['parent id'].iloc[0]: x['id'].tolist()})
df[df['id'].isin(df['parent id'])].apply(lambda x: items[x['parent id']][x['parent id']].append(items[x['id']]), axis=1)
tree = items.iloc[0]

Output:

>>> tree
{0: [{2: [{4: [41, 42, 43]}, {3: [14, 15]}, 11, 12, 13, 16]}, 1]}

Output (formatted):

{
    0: [
        {
            2: [
                {
                    4: [
                        41,
                        42,
                        43
                    ]
                },
                {
                    3: [
                        14,
                        15
                    ]
                },
                11,
                12,
                13,
                16
            ]
        },
        1
    ]
}
  • Related