[pandas DataFrame Correlation Matrix with Colored Entries] Remove lower-tri elements, make large numbers red #python #pandas #color #DataFrame
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
def color_large_value_red(val): | |
""" | |
Takes a scalar and returns a string with | |
the css property `'color: red'` for absolute values > 0.5, | |
black otherwise. | |
""" | |
try: | |
float_val = float(val) | |
color = 'red' if (abs(float_val) > 0.4) and (float_val != 1) else 'black' | |
except: | |
color = 'black' | |
return 'color: %s' % color | |
vars_to_corr = [ | |
'var1', 'var2', | |
] | |
df_corr = df[vars_to_corr].corr().round(decimals=3).astype(str) | |
df_corr.values[np.tril_indices(df_corr.shape[0], k=-1)] = '' | |
rename_func = lambda x: x.replace('what', 'to') | |
df_corr.rename( | |
index=rename_func, | |
columns=rename_func, | |
inplace=True | |
) | |
df_corr.style.applymap(color_large_value_red) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment