Column covariance

If I have a numpy X array with X.shape=(m,n) and a second y column vector with y.shape=(m,1) , how can I calculate the covariance of each X column with y without using a for loop? I expect the result to be in the form (m,1) or (1,m) .

+1
source share
1 answer

Assuming that the output should be in the form (1,n) , i.e. a scalar for each covariance operation for each column A with B and therefore for columns n ending with n such scalars, you can use two approaches that use the covariance formula .

Approach No. 1: with broadcast

 np.sum((A - A.mean(0))*(B - B.mean(0)),0)/B.size 

Approach No. 2: with matrix multiplication

 np.dot((B - B.mean(0)).T,(A - A.mean(0)))/B.size 
+1
source

All Articles