如何获得 Pandas 中两列之间的相关性?
我们可以使用.corr()获取Pandas中两列之间相关性的方法。让我们举个例子,看看如何应用这个方法。
步骤
创建二维、大小可变、潜在异构的表格数据df。
打印输入数据帧df。
初始化两个变量col1和col2,并为它们分配要查找其相关性的列。
使用df[col1].corr(df[col2])找出col1和col2之间的相关性,并将相关值保存在变量corr中。
打印相关值,corr。
示例
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 7, 0],
"y": [4, 7, 5, 1],
"z": [9, 3, 5, 1]
}
)
print "Input DataFrame is:\n", df
col1, col2 = "x", "y"
corr = df[col1].corr(df[col2])
print "之间的相关性 ", col1, " and ", col2, "is: ", round(corr, 2)
col1, col2 = "x", "x"
corr = df[col1].corr(df[col2])
print "之间的相关性 ", col1, " and ", col2, "is: ", round(corr, 2)
col1, col2 = "x", "z"
corr = df[col1].corr(df[col2])
print "之间的相关性 ", col1, " and ", col2, "is: ", round(corr, 2)
col1, col2 = "y", "x"
corr = df[col1].corr(df[col2])
print "之间的相关性 ", col1, " and ", col2, "is: ", round(corr, 2)输出结果Input DataFrame is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 之间的相关性 x and y is: 0.41 之间的相关性 x and x is: 1.0 之间的相关性 x and z is: 0.72 之间的相关性 y and x is: 0.41
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短