6

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?

1
  • Please, could you share corr?
    – yatu
    Dec 17, 2018 at 20:01

3 Answers 3

10

Simply replace triu_indices_from with tril_indices_from:

mask = np.zeros_like(corr, dtype=np.bool)
mask[np.tril_indices_from(mask)] = True
0
1

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
1

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.