为什么 np.corrcoef(x) 和 df.corr() 给出不同的结果?

dan*_*lzz 9 python numpy correlation pandas

为什么使用 np.corrcoef(x) 和 df.corr() 时 numpy 相关系数矩阵和 pandas 相关系数矩阵不同?

x = np.array([[0, 2, 7], [1, 1, 9], [2, 0, 13]]).T
x_df = pd.DataFrame(x)
print("matrix:")
print(x)
print()
print("df:")
print(x_df)
print()

print("np correlation matrix: ")
print(np.corrcoef(x))
print()
print("pd correlation matrix: ")

print(x_df.corr())
print()
Run Code Online (Sandbox Code Playgroud)

给我输出

matrix:
[[ 0  1  2]
 [ 2  1  0]
 [ 7  9 13]]

df:
   0  1   2
0  0  1   2
1  2  1   0
2  7  9  13

np correlation matrix: 
[[ 1.         -1.          0.98198051]
 [-1.          1.         -0.98198051]
 [ 0.98198051 -0.98198051  1.        ]]

pd correlation matrix: 
          0         1         2
0  1.000000  0.960769  0.911293
1  0.960769  1.000000  0.989743
2  0.911293  0.989743  1.000000
Run Code Online (Sandbox Code Playgroud)

我猜它们是不同类型的相关系数?

Pau*_*nan 6

@AlexAlex 是对的,您在相关系数中采用了一组不同的数字。

在 2x3 矩阵中思考

x = np.array([[0, 2, 7], [1, 1, 9]])
np.corrcoef(yx)
Run Code Online (Sandbox Code Playgroud)

给出

array([[1.        , 0.96076892],
       [0.96076892, 1.        ]])
Run Code Online (Sandbox Code Playgroud)

x_df = pd.DataFrame(yx.T)
print(x_df)
x_df[0].corr(x_df[1])
Run Code Online (Sandbox Code Playgroud)

给出

   0  1
0  0  1
1  2  1
2  7  9

0.9607689228305227
Run Code Online (Sandbox Code Playgroud)

其中 0.9607... 等数字与 NumPy 计算的输出匹配。

如果您在计算中这样做,则相当于比较行而不是列的相关性。.T您可以使用或 参数修复 NumPy 版本rowvar=False