Pandas Series.corr() function
Series.corr() is a Pandas function for computing the correlation coefficient between two Series. The correlation coefficient measures the strength of the linear relationship between two variables and ranges from -1 to 1.
A correlation coefficient close to 1 indicates a positive correlation, close to -1 a negative correlation, and close to 0 almost no correlation. It is widely used in data analysis, feature selection, regression analysis, and other scenarios.
Basic syntax and parameters
corr() is a member function of the Series object and requires another Series as an argument.
Syntax format
Series.corr(other, method='pearson', min_periods=None, **kwargs)
Parameter Description
| Parameters | Type | Description | Default value |
|---|---|---|---|
| other | Series | The other Series used to compute the correlation coefficient. | Required |
| method | str | The method used to compute the correlation coefficient. Possible values: 'pearson', 'spearman', 'kendall'. | 'pearson' |
| min_periods | int | The minimum number of valid observations required for the computation. If there are fewer valid values, NaN is returned. | None |
Return Value
- Return Type:
float - Description: Returns the correlation coefficient between two Series, ranging from [-1, 1].
Example
Let us thoroughly master Series.corr() through a series of examples from simple to complex.
Example 1: Basic usage - Pearson correlation coefficient
The Pearson correlation coefficient is the most commonly used one; it measures the linear relationship between two variables.
Example
import
pandas
as
pd
Create two Series: study time and exam scores
study_hours
=
pd.
Series
(
[
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
]
)
exam_scores
=
pd.
Series
(
[
55
,
60
,
65
,
70
,
75
,
80
,
85
,
90
]
)
(
"Study time (hours):"
)
(
study_hours
)
(
)
(
"Exam scores (points):"
)
(
exam_scores
)
(
)
Compute the Pearson correlation coefficient
correlation
=
study_hours.
corr
(
exam_scores
)
(
f
"Pearson correlation coefficient: {correlation:.4f}"
)
(
)
(
"Analysis: the correlation coefficient is close to 1, indicating a strong positive correlation between study time and exam scores."
)
Running result:
学习时间(小时):
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
dtype: int64
考试成绩(分):
0 55
1 60
2 65
3 70
4 75
5 80
6 85
7 90
dtype: int64
皮尔逊相关系数:1.0000
Code analysis:
- A correlation coefficient of 1.0 indicates a perfect positive correlation.
- This means that for each additional hour of study time, the exam score increases by a fixed 5 points.
Example 2: Examples of negative and zero correlation
Demonstrate different types of correlation.
Example
import
pandas
as
pd
Positively correlated data: age and income
ages
=
pd.
Series
(
[
25
,
30
,
35
,
40
,
45
,
50
]
)
income
=
pd.
Series
(
[
4000
,
5000
,
6000
,
7000
,
8000
,
9000
]
)
(
"Positive correlation example - age and income:"
)
(
f
"Correlation coefficient: {ages.corr(income):.4f}"
)
(
)
Negatively correlated data: gaming time and academic performance
game_hours
=
pd.
Series
(
[
1
,
2
,
3
,
4
,
5
,
6
]
)
grades
=
pd.
Series
(
[
95
,
90
,
82
,
75
,
65
,
55
]
)
(
"Negative correlation example - gaming time and academic performance:"
)
(
f
"Correlation coefficient: {game_hours.corr(grades):.4f}"
)
(
)
Uncorrelated data: shoe size and IQ
shoe_sizes
=
pd.
Series
(
[
36
,
37
,
38
,
39
,
40
,
41
]
)
iq_scores
=
pd.
Series
(
[
100
,
105
,
95
,
110
,
98
,
102
]
)
(
"No correlation example - shoe size and IQ:"
)
(
f
"Correlation coefficient: {shoe_sizes.corr(iq_scores):.4f}"
)
(
)
(
"Interpreting the correlation coefficient:"
)
(
" |r| > 0.7: strong correlation"
)
(
" 0.4 < |r| <= 0.7: moderate correlation")
print(" 0.2 < |r| <= 0.4: weak correlation")
print(" |r| <= 0.2: almost no correlation")
Running result:
Positive correlation example - Age and income:
相关系数:1.0000
Negative correlation example - Gaming time and academic performance:
相关系数:-0.9856
No relevant examples - Shoe size and IQ:
相关系数:0.0857
Example 3: Using different correlation methods
Demonstrate the use of Spearman and Kendall correlation coefficients.
Example
import
pandas
as
pd
Create data with a non-linear relationship
x
=
pd.
Series
(
[
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
,
10
]
)
Use an exponential relationship, which is not purely linear
y
=
pd.
Series
(
[
1
,
4
,
9
,
16
,
25
,
36
,
49
,
64
,
81
,
100
]
)
(
"Data X:"
)
(
x
)
(
)
(
"Data Y (X squared):"
)
(
y
)
(
)
Pearson correlation coefficient (measures linear relationships)
pearson_corr
=
x.
corr
(
y
,
method
=
'pearson'
)
(
f
"Pearson correlation coefficient: {pearson_corr:.4f}"
)
Spearman correlation coefficient (measures monotonic relationships)
spearman_corr
=
x.
corr
(
y
,
method
=
'spearman'
)
(
f
"Spearman correlation coefficient: {spearman_corr:.4f}"
)
Kendall correlation coefficient
kendall_corr
=
x.
corr
(
y
,
method
=
'kendall'
)
(
f
"Kendall correlation coefficient: {kendall_corr:.4f}"
)
(
)
(
"Analysis:"
)
(
"Although X and Y have a perfect monotonic relationship (y = x^2),"
)
(
"the Pearson correlation coefficient is not 1 because they are not linearly related."
)
(
"The Spearman and Kendall coefficients are 1 because they measure monotonic relationships."
)
Running result:
数据 X:
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
dtype: int64
数据 Y(X 的平方):
0 1
1 4
2 9
3 16
4 25
5 36
6 49
7 64
8 81
9 100
dtype: int64
皮尔逊相关系数:0.9746
斯皮尔曼相关系数:1.0000
肯德尔相关系数:1.0000
Example 4: Using the min_periods parameter
Control the minimum number of valid observations required for the computation.
Example
import
pandas
as
pd
import
numpy
as
np
Create two Series containing missing values
s1
=
pd.
Series
(
[
1
,
2
,
np.
nan
,
4
,
5
,
np.
nan
,
7
,
8
]
)
s2
=
pd.
Series
(
[
2
,
4
,
6
,
8
,
10
,
12
,
14
,
16
]
)
(
"Series 1:"
)
(
s1
)
(
)
(
"Series 2:"
)
(
s2
)
(
)
By default, at least 2 valid values are required
corr_default
=
s1.
corr
(
s2
)
(
f
"Default (min_periods=None) correlation: {corr_default:.4f}"
)
Set the minimum required valid values to 6
corr_6
=
s1.
corr
(
s2
,
min_periods
=
6
)
(
f
"min_periods=6 correlation: {corr_6:.4f}"
)
Set the minimum required valid values to 7 (only 6 valid values, so NaN is returned)
corr_7
=
s1.
corr
(
s2
,
min_periods
=
7
)
(
f
"min_periods=7 correlation: {corr_7}"
)
Running result:
Series 1:
0 1.0
1 2.0
2 NaN
3 4.0
4 5.0
5 NaN
6 7.0
7 8.0
dtype: float64
Series 2:
0 2
1 4
2 6
3 8
4 10
5 12
6 14
7 16
dtype: int64
默认(min_periods=None)相关系数:1.0000
min_periods=6 相关系数:1.0000
min_periods=7 相关系数:nan
Example 5: Real-world application - analyzing correlations among economic indicators
Demonstrate the use of correlation coefficients in real data analysis.
Example
import
pandas
as
pd
Create simulated macroeconomic data
gdp_growth
=
pd.
Series
(
[
6.5
,
7.2
,
8.1
,
7.8
,
6.9
,
5.5
,
4.8
]
)
unemployment
=
pd.
Series
(
[
4.2
,
3.8
,
3.5
,
3.7
,
4.0
,
4.8
,
5.2
]
)
inflation
=
pd.
Series
(
[
2.1
,
2.5
,
3.2
,
3.0
,
2.4
,
1.8
,
1.5
]
)
stock_index
=
pd.
Series
(
[
3000
,
3200
,
3500
,
3400
,
3100
,
2800
,
2600
]
)
(
"Macroeconomic data:"
)
(
f
"GDP growth rate: {gdp_growth.values}"
)
(
f
"Unemployment rate: {unemployment.values}"
)
(
f
"Inflation rate: {inflation.values}"
)
(
f
"Stock index: {stock_index.values}"
)
(
)
Analyze the correlations among the indicators
(
"Correlation analysis:"
)
(
f
"GDP growth rate vs unemployment rate: {gdp_growth.corr(unemployment):.4f}"
)
(
f
"GDP growth rate vs stock index: {gdp_growth.corr(stock_index):.4f}"
)
(
f
"Unemployment rate vs stock index: {unemployment.corr(stock_index):.4f}"
)
(
f
"Inflation rate vs stock index: {inflation.corr(stock_index):.4f}"
)
(
)
(
"Conclusion:"
)
(
"- GDP growth rate and unemployment rate are negatively correlated (when the economy is strong, unemployment is low)"
)
(
"- GDP growth rate and stock index are strongly positively correlated (when the economy is strong, the stock market rises)"
)
(
"- Unemployment rate and stock index are negatively correlated"
)
Running result:
Macroeconomic data:
GDP 增长率:[6.5 7.2 8.1 7.8 6.9 5.5 4.8]
失业率:[4.2 3.8 3.5 3.7 4. 4. 5.2]
通胀率:[2.1 2.5 3.2 3. 2.4 1.8 1.5]
股指:[3000 3200 3500 3400 3100 2800 2600]
Correlation analysis:
GDP 增长率 vs 失业率:-0.9036
GDP 增长率 vs 股指:0.9434
失业率 vs 股指:-0.9712
通胀率 vs 股指:-0.9712
Code analysis:
- The correlation coefficient between GDP growth rate and unemployment rate is -0.9036, a strong negative correlation.
- The correlation coefficient between GDP growth rate and stock index is 0.9434, a strong positive correlation.
- These correlations align with economic intuition.
Notes
- Correlation coefficients can only measure linear relationships and may be inaccurate for non-linear ones.
- A correlation coefficient near 0 does not mean there is no relationship; a non-linear relationship may exist.
- Correlation does not imply causation; business context is needed for judgment.
- The Spearman correlation coefficient is suitable for ranked data or non-linear monotonic relationships.
- The Kendall correlation coefficient is more robust to noise in the data, but slower to compute.
Summary
Series.corr() is a powerful tool for analyzing the relationship between two variables. Its main features include:
- Supports three correlation methods: Pearson, Spearman, and Kendall.
- The Pearson coefficient is suitable for measuring linear relationships.
- The Spearman and Kendall coefficients are suitable for measuring monotonic relationships.
- You can control the minimum number of valid observations.
In practice, correlation coefficients are often used for feature selection, data exploration, and hypothesis testing. Note, however, that correlation analysis can only reveal statistical associations and cannot directly infer causation.
Common Pandas functions