How to convert numpy.nd array to DistanceMatrix class?

Hello,
Suppose I have a numpy.nd array named “arr” which is distance matrix. I want to convert it to DistanceMatrix class such that type(arr) will be DistanceMatrix. This is because I want to use biopython package to draw a tree where

from Bio import Phylo
from Bio.Phylo.TreeConstruction import DistanceTreeConstructor
constructor=DistanceTreeConstructor()
tree=constructor.nj(arr)

arr should be of type DistanceMatrix and I have csv version of it.

Convert your numpy array to python lists.

Then you can do something like this:

>>> from Bio.Phylo.TreeConstruction import _Matrix
>>> names = ['Alpha', 'Beta', 'Gamma', 'Delta']
>>> matrix = [[0], [1, 0], [2, 3, 0], [4, 5, 6, 0]]
>>> m = _Matrix(names, matrix)
>>> m
_Matrix(names=['Alpha', 'Beta', 'Gamma', 'Delta'], matrix=[[0], [1, 0], [2, 3, 0], [4, 5, 6, 0]])
>>> print m
Alpha   0
Beta    1   0
Gamma   2   3   0
Delta   4   5   6   0
    Alpha   Beta    Gamma   Delta

Source: _Matrix - Other Useful Classes - Phylo - BioPython

1 Like