Python generate a mask for the lower triangle of a matrix

Viewed 5060

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?

3 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

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

You can simply transpose the mask that you have:

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