Only show value of n*n matrix if value from another n*n has a certain value (Python)
<p>So I'm currently trying to calculate the Pearson's R and p-value for some data I have. This is done by this code:</p>

<pre><code>import numpy as np
from scipy.stats import pearsonr, betai
from pandas import DataFrame
import seaborn as sns
import matplotlib.pyplot as plt

def corrcoef(matrix): #function that calculates the Pearson's R and p-value
    r = np.corrcoef(matrix)
    rf = r[np.triu_indices(r.shape[0], 1)]
    df = matrix.shape[1] - 2
    ts = rf * rf * (df / (1 - rf * rf))
    pf = betai(0.5 * df, 0.5, df / (df + ts))
    p = np.zeros(shape=r.shape)
    p[np.triu_indices(p.shape[0], 1)] = pf
    p[np.tril_indices(p.shape[0], -1)] = pf
    p[np.diag_indices(p.shape[0])] = np.ones(p.shape[0])
    return r, p

data = np.loadtxt('corr-data.txt') #data matrix loaded

sig_lvl = 0.05 #significance level

r_mat, p_mat = corrcoef(data) #use function on data and put the answers in two different matrices

df_rmat = DataFrame(r_mat, columns=Index, index=Index) #make data readable for the seaborn package
df_pmat = DataFrame(p_mat, columns=Index, index=Index)

r_mat[abs(r_mat) &lt;= .90] = np.nan #if the R-value matrix elements are under 0.90, don't show them - make them NaN. 
p_mat[abs(p_mat) &gt;= sig_lvl] = np.nan #this is probably the issue.

mask_pmat = np.zeros_like(p_mat)
mask_pmat[np.tril_indices_from(mask_pmat)] = True #only showing the upper triangle of the values since it's symmetrical in the diagonal

sns.plt.subplot(1,2,2)
ax_pmat = sns.heatmap(np.around(df_pmat, decimals=2), annot=True, mask = mask_pmat) #subplot sequence for the p-value matrix only

sns.plt.show()
</code></pre>

<p>It might not be the most optimal code, but as of now it works as intended. Using the seaborn package I get a heat/colormap of the different values if they are high enough (>= 0.95) or have the right significance level, and only the upper triangle. However, what I would actually like to do is to only show the p-value for those R-values that are represented in the first plot. Values that are smaller than 0.95 is just replaced by NaN and is no color in the heat map. So only values in the p-value matrix should be represented if values in the R-value matrix is represented.</p>

<p>Can this be done, or...?</p>

<p>And please let me know if something is unclear. Then I will try to further explain.</p>

<p>Thanks in advance</p>

<p>I think what you're saying is this:</p>

<pre><code>p_mat[r_mat &lt; 0.95] = np.nan
</code></pre>

<p>This works because <code>p</code> and <code>r</code> are the same shape.  It would go into your code instead of:</p>

<pre><code>if r_mat[abs(r_mat) &lt;= .90] == np.nan:
    p_mat = np.nan
</code></pre>

<p>Note if you compare <code>NaN</code> to a value, the result is always false.</p>

python numpy matplotlib scipy seaborn