def sort_matrix(mat):
    """Sorts a 2D matrix, first by its rows and then by its columns.

    Parameters
    ----------
    mat : pd.DataFrame
        Matrix to sort.

    Returns
    -------
    pd.DataFrame
        Sorted matrix.

    """

    freqs = (mat > 0).sum(axis=1)
    order = list(freqs.sort_values(ascending=False).index)

    mat_sorted = mat.ix[order]
    mat_sorted = mat_sorted.T.sort_values(by=order, ascending=False).T

    return mat_sorted