def sort_matrix(df, sort_columns=True):
    """Sorts a DataFrame, first by its columns and then by its rows."""

    if sort_columns:
        freqs = (df.astype(float) > 0).sum(axis=0)
        order = list(freqs.sort_values(ascending=False).index)
    else:
        order = list(df.columns)

    df_sorted = df[order]
    df_sorted = df_sorted.sort_values(by=order, ascending=False)

    return df_sorted