一、简介
dataframe.corr()
是pandas库中的一个函数,用于计算dataframe中各列之间的相关系数。相关系数衡量的是两个变量之间线性关系的强度和方向,结果在-1到1之间,分别表示完全负相关和完全正相关。
二、语法和参数
dataframe.corr(method='pearson', min_periods=1)
method: 可选。计算相关系数的方法,有’pearson’(默认)、‘kendall’、'spearman’三种可选。
'pearson'
:标准皮尔逊相关系数。'kendall'
:肯德尔等级相关系数。'spearman'
:斯皮尔曼等级相关系数。
min_periods: 可选。每对元素的最小数量,以便计算相关系数。
三、实例
3.1 计算默认的皮尔逊相关系数
import pandas as pd # 创建示例数据 data = { 'a': [1, 2, 3, 4, 5], 'b': [5, 4, 3, 2, 1], 'c': [2, 2, 3, 4, 4] } df = pd.dataframe(data) # 计算相关系数 correlation_matrix = df.corr() print(correlation_matrix)
输出:
a b c
a 1.000000 -1.000000 0.948683
b -1.000000 1.000000 -0.948683
c 0.948683 -0.948683 1.000000
3.2 计算斯皮尔曼相关系数
import pandas as pd # 创建示例数据 data = { 'a': [1, 2, 3, 4, 5], 'b': [5, 4, 3, 2, 1], 'c': [2, 2, 3, 4, 4] } df = pd.dataframe(data) # 计算相关系数 correlation_matrix = df.corr(method='spearman') print(correlation_matrix)
输出:
a b c
a 1.000000 -1.000000 0.948683
b -1.000000 1.000000 -0.948683
c 0.948683 -0.948683 1.000000
3.3 计算斯皮尔曼相关系数
import pandas as pd # 创建示例数据 data = { 'a': [1, 2, 3, 4, 5], 'b': [5, 4, 3, 2, 1], 'c': [2, 2, 3, 4, 4] } df = pd.dataframe(data) # 计算相关系数 correlation_matrix = df.corr(method='kendall') print(correlation_matrix)
输出
a b c
a 1.000000 -1.000000 0.894427
b -1.000000 1.000000 -0.894427
c 0.894427 -0.894427 1.000000
四、注意事项
- 当使用
kendall
和spearman
方法时,计算可能会比pearson
方法慢,因为这些方法需要排序。 - 如果数据集中存在
nan
值,默认情况下这些值会被忽略。 - 计算相关系数前,确保数据已经清洗并准备好,以避免错误或不准确的结果。
到此这篇关于pandas库中dataframe.corr()函数的使用的文章就介绍到这了,更多相关pandas dataframe.corr()函数内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论