Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python generate a mask for the lower triangle of a matrix

I have this code from seaborn documentation to generate a mask for the upper triangle of a given correlation matrix

# Compute the correlation matrix
corr = d.corr()

# Generate a mask for the upper triangle

mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True

how would one achieve the invert, a mask for the lower triangle?

like image 755
Charles David Mupende Avatar asked Dec 17 '18 19:12

Charles David Mupende


2 Answers

Simply replace triu_indices_from with tril_indices_from:

mask = np.zeros_like(corr, dtype=np.bool)
mask[np.tril_indices_from(mask)] = True
like image 95
MEE Avatar answered Sep 30 '22 18:09

MEE


Take the transpose of your matrix:

mask = mask.T

mask
array([[ True, False, False, False, False],
       [ True,  True, False, False, False],
       [ True,  True,  True, False, False],
       [ True,  True,  True,  True, False],
       [ True,  True,  True,  True,  True]])

mask.T
array([[ True, False, False, False, False],
       [ True,  True, False, False, False],
       [ True,  True,  True, False, False],
       [ True,  True,  True,  True, False],
       [ True,  True,  True,  True,  True]])

However this is more of a workaround, the correct solution is @john 's

like image 35
yatu Avatar answered Sep 30 '22 20:09

yatu