def hclust_linearize ( U ) : from scipy . cluster import hierarchy Z = hierarchy . ward ( U ) return hierarchy . leaves_list ( hierarchy . optimal_leaf_ordering ( Z , U ) )
use sparse matrices with agglomerativeclustering in python
Sorts the rows of a matrix by hierarchical clustering .
def hclust_linearize(U):
    """Sorts the rows of a matrix by hierarchical clustering.

    Parameters:
        U (ndarray) : matrix of data

    Returns:
        prm (ndarray) : permutation of the rows
    """

    from scipy.cluster import hierarchy
    Z = hierarchy.ward(U)
    return hierarchy.leaves_list(hierarchy.optimal_leaf_ordering(Z, U))