Confounded
Confounded

Reputation: 522

numpy: calculate cross-covariance, without calculating the whole covariance matrix

The numpy.cov(x, y) with 1-d array inputs returns the entire 2x2 covariance matrix. Is there a way to calculate only the cross-covariance, i.e. E[xy] - E[x]E[y] without wasting time on calculating the two variances?

PS. How does one write equations on here? The $$ does not seem to work as it does on other Stack websites.

Upvotes: 3

Views: 3727

Answers (1)

nocibambi
nocibambi

Reputation: 2431

What's wrong with simply implementing the equation you wrote?

# E[xy] - E[x]E[y]
cov = (x * y).mean() - x.mean() * y.mean()

Upvotes: 3

Related Questions