如何在Pandas中计算两列之间的相关关系

如何在Pandas中计算两列之间的相关关系

在这篇文章中,我们将讨论如何在pandas中计算两列之间的相关关系

相关是用来总结两个定量变量之间的线性关联的强度和方向。它用r表示,数值在-1和+1之间。r的正值表示正相关,而r的负值表示负相关。

通过使用corr()函数,我们可以得到数据框架中两列之间的相关关系。

语法 :

dataframe[first_column].corr(dataframe[second_column])
Python

其中,

  • dataframe是输入数据帧
  • 第一列与数据框架的第二列相关联

例子1 :获得两列之间相关性的Python程序

# import pandas module
import pandas as pd
 
# create dataframe with 3 columns
data = pd.DataFrame({
    "column1": [12, 23, 45, 67],
    "column2": [67, 54, 32, 1],
    "column3": [34, 23, 56, 23]
}
)
# display dataframe
print(data)
 
# correlation between column 1 and column2
print(data['column1'].corr(data['column2']))
 
# correlation between column 2 and column3
print(data['column2'].corr(data['column3']))
 
# correlation between column 1 and column3
print(data['column1'].corr(data['column3']))
Python

输出:

 column1  column2  column3
0       12       67       34
1       23       54       23
2       45       32       56
3       67        1       23
-0.9970476685163736
0.07346999975265099
0.0
Python

也可以只用corr()函数来获得数值列的元素间的相关关系。

语法:

dataset.corr()
Python

例子2 :获得元素间的相关关系

# import pandas module
import pandas as pd
 
# create dataframe with 3 columns
data = pd.DataFrame({
    "column1": [12, 23, 45, 67],
    "column2": [67, 54, 32, 1],
    "column3": [34, 23, 56, 23]
}
)
# get correlation between element wise
print(data.corr())
Python

输出 :

          column1   column2  column3
column1  1.000000 -0.997048  0.00000
column2 -0.997048  1.000000  0.07347
column3  0.000000  0.073470  1.00000
Python

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册