w3resource

NumPy: Compute pearson product-moment correlation coefficients of two given arrays

NumPy Statistics: Exercise-10 with Solution

Write a NumPy program to compute pearson product-moment correlation coefficients of two given arrays.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating an array 'x' containing elements [0, 1, 3]
x = np.array([0, 1, 3])

# Creating an array 'y' containing elements [2, 4, 5]
y = np.array([2, 4, 5])

# Displaying the original array 'x'
print("\nOriginal array1:")
print(x)

# Displaying the original array 'y'
print("\nOriginal array1:")
print(y)

# Calculating the Pearson product-moment correlation coefficients of arrays 'x' and 'y' using np.corrcoef()
print("\nPearson product-moment correlation coefficients of the said arrays:\n", np.corrcoef(x, y))

Sample Output:

Original array1:
[0 1 3]

Original array1:
[2 4 5]

Pearson product-moment correlation coefficients of the said arrays:
 [[1.         0.92857143]
 [0.92857143 1.        ]]

Explanation:

In the above code –

x = np.array([0, 1, 3]): This creates a NumPy array x with values [0, 1, 3].

y = np.array([2, 4, 5]): This creates a NumPy array y with values [2, 4, 5].

print(np.corrcoef(x, y)): This computes the correlation matrix between x and y, and prints it to the console.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to compute cross-correlation of two given arrays.
Next: Write a NumPy program to test element-wise of a given array for finiteness (not infinity or not Not a Number), positive or negative infinity, for NaN, for NaT (not a time), for negative infinity, for positive infinity.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-stat-exercise-10.php