How to convert pandas DataFrame to dictionary for Newick format

I have the following dataset:

import pandas as pd
df = pd.DataFrame([['root', 'b', 'a', 'leaf1'],
                   ['root', 'b', 'a', 'leaf2'],
                   ['root', 'b', 'leaf3', ''],
                   ['root', 'b', 'leaf4', ''],
                   ['root', 'c', 'leaf5', ''],
                   ['root', 'c', 'leaf6', '']],
                   columns=['col1', 'col2', 'col3', 'col4'])

Because I have found no way to directly convert it into Newic format, I would like to convert it into a dictionary with the following format:

node_to_children = {
    'root': {'b': 0, 'c': 0},
    'a': {'leaf1': 0, 'leaf2': 0},
    'b': {'a': 0, 'leaf3': 0, 'leaf4': 0},
    'c': {'leaf5': 0, 'leaf6': 0}

Then I can ultimately convert this node_to_children into Newic format, however, how can I make the conversion from the pandas DataFrame to dictionary?


I assumed that every row in your dataframe stands for one complete branch of the tree from the root to the leaves. Based on this, I came up with the following solution. Comments to each step in the algorithm can be found in the code below, but feel free to ask if anything is unclear.

node_to_children = {}

#iterate over dataframe row-wise. Assuming that every row stands for one complete branch of the tree
for row in df.itertuples():
    #remove index at position 0 and elements that contain no child ("")
    row_list = [element for element in row[1:] if element != ""]
    for i in range(len(row_list)-1):
        if row_list[i] in node_to_children.keys():
            #parent entry already existing 
            if row_list[i+1] in node_to_children[row_list[i]].keys():
                #entry itself already existing --> next
                #entry not existing --> update dict and add the connection
            #add the branching point
            node_to_children[row_list[i]] = {row_list[i+1]:0}


{'root': {'b': 0, 'c': 0}, 
 'b': {'a': 0, 'leaf3': 0, 'leaf4': 0}, 
 'a': {'leaf1': 0, 'leaf2': 0}, 
 'c': {'leaf5': 0, 'leaf6': 0}}