Created
June 14, 2022 17:07
-
-
Save alexlenail/014dec095100ff4e17ce130414c70c52 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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