Inverse scipy.spatial.distance.squareform function

Is there a reverse scipy.spatial.distance.squareform function? If not, what is the best way to write to handle the huge matrix of distances?

+3


source to share


2 answers


According to the docs squareform

is its own reverse:



http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.squareform.html

+6


source


Actually, this lambda is quite efficient:

In [1]: unsquareform = lambda a: a[numpy.nonzero(numpy.triu(a))]

      

For example:



In [2]: scipy.spatial.distance.pdist(numpy.arange(12).reshape((4,3)))
Out[2]:
array([  5.19615242,  10.39230485,  15.58845727,   5.19615242,
        10.39230485,   5.19615242])

      

and

In [3]: unsquareform(scipy.spatial.distance.squareform(scipy.spatial.distance.pdist(numpy.arange(12).reshape((4,3)))))
Out[3]:
array([  5.19615242,  10.39230485,  15.58845727,   5.19615242,
        10.39230485,   5.19615242])

      

+1


source







All Articles