python-scipyHow do I calculate the correlation coefficient in Python using SciPy?
The correlation coefficient can be calculated in Python using SciPy's pearsonr function. This function takes two arrays of equal length and returns the Pearson correlation coefficient and the p-value for testing non-correlation. The Pearson correlation coefficient is a measure of the linear correlation between two variables.
Example code
from scipy.stats import pearsonr
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
corr, p_value = pearsonr(x, y)
print(corr)
Output example
1.0
The code consists of four parts:
- Importing the Pearson correlation coefficient function from the SciPy package.
- Defining two arrays of equal length.
- Calculating the Pearson correlation coefficient and the p-value for testing non-correlation by calling the
pearsonrfunction with the two arrays as arguments. - Printing the Pearson correlation coefficient.
Helpful links
More of Python Scipy
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How do I create a 2D array of zeros using Python and NumPy?
- How can I use Python Numpy to select elements from an array based on multiple conditions?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How do I upgrade my Python Scipy package?
- How can I use Python and SciPy to read and write WAV files?
- How do I use the trapz function in Python SciPy?
- How do I rotate an image using Python and SciPy?
- How do I use Python Scipy's Odeint function?
- How do I install SciPy for Python?
See more codes...