Skip to content

Instantly share code, notes, and snippets.

@alexlenail
Created June 14, 2022 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexlenail/014dec095100ff4e17ce130414c70c52 to your computer and use it in GitHub Desktop.
Save alexlenail/014dec095100ff4e17ce130414c70c52 to your computer and use it in GitHub Desktop.
import scipy
import scipy.stats
from scipy.cluster.hierarchy import dendrogram, linkage
from scipy.cluster import hierarchy
def sort_df_by_hclust_olo(df, how='both', method='ward', metric='euclidean'):
'''
how={'index', 'columns', 'both'}
'''
df = df.fillna(0)
if how in ['index', 'both']:
Z = linkage(df, method=method, metric=metric)
order = hierarchy.leaves_list(hierarchy.optimal_leaf_ordering(Z, df))
df = df.iloc[order]
if how in ['columns', 'both']:
df = df.T
Z = linkage(df, method=method, metric=metric)
order = hierarchy.leaves_list(hierarchy.optimal_leaf_ordering(Z, df))
df = df.iloc[order].T
return df.replace(0, np.nan)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment