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:
- Pearson correlation coefficient: Measures the linear relationship between variables, applicable to numeric variables.
- Spearman rank correlation coefficient: Measures the monotonic relationship between variables, applicable to numeric and ordinal variables.
- Kendall rank correlation coefficient: Measures the rank relationship between variables, applicable to small-sample data.
- Correlation matrix: Used to view the correlation between variables.
- Heatmap: An effective visualization method that helps us visually inspect the correlations 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.
- Positive correlation: When one variable increases, the other also increases. For example, there may be a positive correlation between height and weight.
- Negative correlation: When one variable increases, the other decreases. For example, there may be a negative correlation between temperature and heating usage.
- No correlation: There is no clear relationship between the two variables.
The value of correlation typically ranges from -1 to 1:
- 1: Perfect positive correlation
- -1: Perfect negative correlation
- 0: No linear correlation
- Close to 1 or -1: Indicates a strong correlation
- Close to 0: Indicates a weak correlation
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:
- method (Optional): A string specifying the method used to compute the correlation coefficient. The default is 'pearson'; you can also choose 'kendall' (Kendall Tau correlation coefficient) or 'spearman' (Spearman rank correlation coefficient).
- min_periods (Optional): The minimum number of observations required to compute the correlation coefficient. The default is 1, meaning that as long as there is at least one non-null value, the computation will be performed. If specified,
min_periods, and the number of non-null values in some columns is less than this value, the correlation coefficient for those columns will be set to NaN.
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'
)
(
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:
corr()method computes the Pearson correlation coefficient between each pair of variables.method='pearson'is the default method, indicating computation of the Pearson correlation coefficient.- As you can see,
HeightThe difference betweenWeightandAgeall have a strong positive correlation.
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'
)
(
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'
)
(
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
(
)
(
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.