You need the Z matrix of links, which is the input to the scipy dendrogram function and converts it to Newick format. In addition, you need a list of "leaf_names" with the names of your leaves. Here is the function that will complete the task:
from scipy.cluster import hierarchy def getNewick(node, newick, parentdist, leaf_names): if node.is_leaf(): return "%s:%.2f%s" % (leaf_names[node.id], parentdist - node.dist, newick) else: if len(newick) > 0: newick = "):%.2f%s" % (parentdist - node.dist, newick) else: newick = ");" newick = getNewick(node.get_left(), newick, node.dist, leaf_names) newick = getNewick(node.get_right(), ",%s" % (newick), node.dist, leaf_names) newick = "(%s" % (newick) return newick tree = hierarchy.to_tree(Z,False) getNewick(tree, "", tree.dist, leaf_names)
source share