Skip to content

Instantly share code, notes, and snippets.

@joonro
Created July 25, 2019 05:02
Show Gist options
  • Save joonro/1559368df9bb65747b70ecf1ddf892f1 to your computer and use it in GitHub Desktop.
Save joonro/1559368df9bb65747b70ecf1ddf892f1 to your computer and use it in GitHub Desktop.
[pandas DataFrame Correlation Matrix with Colored Entries] Remove lower-tri elements, make large numbers red #python #pandas #color #DataFrame
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