Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

6.2 Correlations

Many Python packages, such as numpy, scipy, and pandas offer functionalities for correlation analysis. As we often work with data in the form of Pandas DataFrames, we will use the pandas package for now.

Let’s start by creating a simple DataFrame containing an x and y variable:

    X   Y
0  10   2
1  11   1
2  12   4
3  13   5
4  14   8
5  15  12
6  16  18
7  17  25
8  18  96
9  19  48

We can then calculate the correlation between these two variables by using the .corr() method. By default, this method calculates Pearson’s correlation coefficient:

Pearson's correlation: 0.7586402890911867

The .corr() method also allows you to use rank correlations (Spearman, Kendall) thrugh the method parameter. For example, you can calculate Spearman’s rank correlation as follows:

Spearman correlation: 0.9757575757575757

Correlation Matrices

If we want to compute correlations for multiple variables, handling individual correlations will not be feasible. In such cases, we can calculate and use correlation matrices, which contain all pairwise correlations. Let’s start by creating a new DataFrame with four variables and then compute the correlation matrix, rounding the results to two decimal places:

      A     B     C     D
A  1.00  0.76 -0.99  0.67
B  0.76  1.00 -0.75  0.35
C -0.99 -0.75  1.00 -0.67
D  0.67  0.35 -0.67  1.00

To make the results more visually appealing, we can plot the correlation matrix as a heatmap using the seaborn library:

<Figure size 640x480 with 2 Axes>