如何使用 Python Pandas 执行三变量相关

5 correlation python-2.7 pandas

Pandascorr()函数将其使用限制为成对计算。但是,如何使用薪水作为下面数据框中的因变量来计算数据框中三个变量的相关性?

    GPA    IQ    SALARY
0   3.2    100   45000
1   4.0    140  150000
2   2.9    90    30000
3   2.5    85    25000
4   3.6    120   75000
5   3.4    110   60000
6   3.0    05    38000
Run Code Online (Sandbox Code Playgroud)

小智 6

您可以通过首先获取 Pandas 对的相关系数来计算因变量与其他两个自变量的相关性。然后您可以使用多重相关系数函数来计算 R 平方,但是这会略有偏差,因此您可以选择更准确的调整 R 平方值。您还可以调整方程以考虑更多的自变量。以下是Charles Zaiontz先生一篇优秀文章的python改编。http://www.real-statistics.com/correlation/multiple-correlation/

import math

df = pd.DataFrame({
    'IQ':[100,140,90,85,120,110,95], 
    'GPA':[3.2,4.0,2.9,2.5,3.6,3.4,3.0],
    'SALARY':[45e3,150e3,30e3,25e3,75e3,60e3,38e3]
    })

# Get pairwise correlation coefficients
cor = df.corr()

# Independent variables
x = 'IQ'
y = 'GPA'

# Dependent variable
z = 'SALARY'

# Pairings
xz = cor.loc[ x, z ]
yz = cor.loc[ y, z ]
xy = cor.loc[ x, y ]

Rxyz = math.sqrt((abs(xz**2) + abs(yz**2) - 2*xz*yz*xy) / (1-abs(xy**2)) )
R2 = Rxyz**2

# Calculate adjusted R-squared
n = len(df) # Number of rows
k = 2       # Number of independent variables
R2_adj = 1 - ( ((1-R2)*(n-1)) / (n-k-1) )
Run Code Online (Sandbox Code Playgroud)

R2,R2_adj = 0.958, 0.956

结果表明,薪水几乎 96% 取决于/与智商和 GPA 相关。