Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas Correlation Analysis

Pandas Correlation Analysis

Correlation analysis is a common and important step in data analysis; it helps us understand the relationships between different variables in the data.

In Pandas, data correlation analysis understands relationships between variables by computing the correlation coefficients between them.

In Pandas, data correlation is an important analytical task that helps us understand the relationships among the variables in the data.

Pandas provides multiple methods to compute and analyze data correlation. Common correlation methods include the Pearson correlation coefficient (Pearson), the Spearman rank correlation coefficient (Spearman), and the Kendall rank correlation coefficient (Kendall).

The following correlation methods can help us reveal linear, nonlinear, or monotonic relationships between variables:

What is correlation?

Correlation indicates the strength and direction of the relationship between two or more variables. Based on the correlation value, we can judge the relationship between variables.

The value of correlation typically ranges from -1 to 1:


Methods for computing correlation in Pandas

Pandas provides the DataFrame.corr() and DataFrame.cov() method to compute correlation and covariance.

Pandas uses the corr() method to compute the relationship between each column in a dataset.

df.corr(method='pearson', min_periods=1)

Parameter Description:

The df.corr() method returns a correlation coefficient matrix, where the rows and columns correspond to the DataFrame's column names, and the elements are the correlation coefficients between the corresponding columns.

Common correlation coefficients include the Pearson correlation coefficient and the Spearman rank correlation coefficient:

Pearson correlation coefficient

Pearson, also known as the Pearson correlation coefficient, measures the strength and direction of the linear relationship between two variables. Its value ranges from -1 to 1, where -1 indicates a perfect negative correlation, 1 a perfect positive correlation, and 0 no linear correlation.

The Pearson correlation coefficient measures the linear relationship between two variables; its formula is:

Pandas can use the corr() method to compute the Pearson correlation coefficient between the columns of a DataFrame.

Pearson correlation coefficient

Example

import

pandas

as

pd

Sample data

data

=

{

   

'Height'

:

[

150

,

160

,

170

,

180

,

190

]

,

   

'Weight'

:

[

45

,

55

,

65

,

75

,

85

]

,

   

'Age'

:

[

20

,

25

,

30

,

35

,

40

]

}

df

=

pd.

DataFrame

(

data

)

Compute the Pearson correlation coefficient

correlation

=

df.

corr

(

method

=

'pearson'

)

print

(

correlation

)

Output result:



        Height  Weight  Age

Height     1.0     1.0  1.0

Weight     1.0     1.0  1.0

Age        1.0     1.0  1.0

Description:

Spearman rank correlation coefficient (Spearman Correlation)

The Spearman correlation coefficient measures the monotonic relationship (whether linear or nonlinear) between two variables and is computed based on the ranks of the variables. Its value range is the same as the Pearson correlation coefficient: -1 to 1.

Example

import

pandas

as

pd

Sample data

data

=

{

   

'Height'

:

[

150

,

160

,

170

,

180

,

190

]

,

   

'Weight'

:

[

45

,

55

,

65

,

75

,

85

]

,

   

'Age'

:

[

20

,

25

,

30

,

35

,

40

]

}

df

=

pd.

DataFrame

(

data

)

Compute the Spearman rank correlation coefficient

spearman_correlation

=

df.

corr

(

method

=

'spearman'

)

print

(

spearman_correlation

)

Output result:



        Height  Weight  Age

Height     1.0     1.0  1.0

Weight     1.0     1.0  1.0

Age        1.0     1.0  1.0

**Note:** method='spearman' computes the Spearman rank correlation coefficient. In this example, because the data grows linearly, the Spearman correlation coefficient is the same as the Pearson correlation coefficient.

Kendall rank correlation coefficient (Kendall Correlation)

The Kendall rank correlation coefficient also measures the monotonic relationship between variables; it is derived by computing the consistency between the ranks of two variables.

The Kendall correlation coefficient is more complex to compute and is suitable for smaller datasets.

Example

import

pandas

as

pd

Sample data

data

=

{

   

'Height'

:

[

150

,

160

,

170

,

180

,

190

]

,

   

'Weight'

:

[

45

,

55

,

65

,

75

,

85

]

,

   

'Age'

:

[

20

,

25

,

30

,

35

,

40

]

}

df

=

pd.

DataFrame

(

data

)

Compute the Kendall rank correlation coefficient

kendall_correlation

=

df.

corr

(

method

=

'kendall'

)

print

(

kendall_correlation

)

Output result:



        Height  Weight  Age

Height     1.0     1.0  1.0

Weight     1.0     1.0  1.0

Age        1.0     1.0  1.0

**Note:** method='kendall' computes the Kendall rank correlation coefficient. In this case, the data changes monotonically, so the result is the same as Pearson and Spearman.


Correlation matrix

The correlation matrix is a symmetric matrix in which each value represents the correlation coefficient between two variables.

You can directly compute the correlation matrix of all variables in a DataFrame using the corr() method.

Example

import

pandas

as

pd

Sample data

data

=

{

   

'Height'

:

[

150

,

160

,

170

,

180

,

190

]

,

   

'Weight'

:

[

45

,

55

,

65

,

75

,

85

]

,

   

'Age'

:

[

20

,

25

,

30

,

35

,

40

]

}

df

=

pd.

DataFrame

(

data

)

Compute the correlation matrix

correlation_matrix

=

df.

corr

(

)

print

(

correlation_matrix

)

Output result:



        Height  Weight  Age

Height     1.0     1.0  1.0

Weight     1.0     1.0  1.0

Age        1.0     1.0  1.0

**Note:** The correlation matrix helps us quickly identify which variables have strong linear or monotonic relationships. In practical analysis, the correlation matrix is very helpful for feature selection and dimensionality reduction.


Correlation Heatmap

To present the correlation matrix more intuitively, you can use a heatmap to visualize the correlations between variables.

Using the seaborn library to draw a correlation heatmap is a common practice.

Example

import

seaborn

as

sns

import

matplotlib.

pyplot

as

plt

import

pandas

as

pd

Sample data

data

=

{

   

'Height'

:

[

150

,

160

,

170

,

180

,

190

]

,

   

'Weight'

:

[

45

,

55

,

65

,

75

,

85

]

,

   

'Age'

:

[

20

,

25

,

30

,

35

,

40

]

}

df

=

pd.

DataFrame

(

data

)

Draw a correlation heatmap

plt.

figure

(

figsize

=

(

8

,

6

)

)

sns.

heatmap

(

df.

corr

(

)

,

annot

=

True

,

cmap

=

'coolwarm'

,

fmt

=

'.2f'

,

vmin

=

1

,

vmax

=

1

)

plt.

title

(

'Correlation Heatmap'

)

plt.

show

(

)

The display is as follows:

**Note:** sns.heatmap() draws the correlation heatmap, annot=True displays the values on the heatmap, cmap='coolwarm' sets the color range, and vmin=-1, vmax=1 limits the color range from -1 to 1.


Visualize correlation

Here we use Python's Seaborn library. Seaborn is a data visualization library based on Matplotlib that focuses on drawing statistical graphics and aims to simplify the process of data visualization.

Seaborn provides simple high-level interfaces that make it easy to draw various statistical graphics, including scatter plots, line plots, bar charts, heatmaps, and more, with good aesthetic results.

Install Seaborn:

pip install seaborn

Example

import

seaborn

as

sns

import

matplotlib.

pyplot

as

plt

import

pandas

as

pd

Create a sample DataFrame

data

=

{

'A'

:

[

1

,

2

,

3

,

4

,

5

]

,

'B'

:

[

5

,

4

,

3

,

2

,

1

]

}

df

=

pd.

DataFrame

(

data

)

Compute the Pearson correlation coefficient

correlation_matrix

=

df.

corr

(

)

Visualize the Pearson correlation coefficient using a heatmap

sns.

heatmap

(

correlation_matrix

,

annot

=

True

,

cmap

=

'coolwarm'

,

fmt

=

".2f"

)

plt.

show

(

)

**Note:** This code generates a heatmap in which colors represent the strength of the correlation coefficient: positive correlations are shown in warm tones and negative correlations in cool tones.annot=True parameter displays the specific values on the heatmap.


Applications of correlation analysis

1. Feature selection

In machine learning modeling, correlation analysis is often used for feature selection. By analyzing the correlations between different features, it helps us select the features most relevant to the target variable and remove redundant features that are highly correlated with others, thereby improving model performance and efficiency.

2. Handling multicollinearity

If the correlation between two or more features is very high (close to 1 or -1), then those features have a multicollinearity problem. In regression analysis, multicollinearity leads to model instability and inaccurate predictions. Multicollinearity can be resolved by removing or combining highly correlated features.