Home > Software design >  Is there a numpy (or Python) function to correlate each columns of 2D numpy array (n,m)
Is there a numpy (or Python) function to correlate each columns of 2D numpy array (n,m)

Time:12-16

I have two numpy matrices (6 rows and 3 columns) :

a = np.array([[1,2,4],[3,6,2],[3,4,7],[9,7,7],[6,3,1],[3,5,9]])

b = np.array([[4,5,2],[9,2,5],[1,5,6],[4,5,6],[1,2,6],[6,4,3]])

a = array([[1, 2, 4],
       [3, 6, 2],
       [3, 4, 7],
       [9, 7, 7],
       [6, 3, 1],
       [3, 5, 9]])

b = array([[4, 5, 2],
       [9, 2, 5],
       [1, 5, 6],
       [4, 5, 6],
       [1, 2, 6],
       [6, 4, 3]])

I would like to calculate the pearson correlation coefficient between the first column of a and b, the second column of a and b and the third column of a and b. The result would be a vector of 3 (3 correlation coeff).

CodePudding user response:

One way using numpy.corrcoef and diagonal:

corr = np.corrcoef(a.T, b.T).diagonal(a.shape[1])
corr

Output:

array([-0.2324843 , -0.03631365, -0.18057878])
  • Related