您如何使用多列计算 pandas 中的(非自)相关矩阵?

How do you calculate a (non-self) correlation matrix in pandas with multicolumns?

假设我有一个包含多列的 pandas 数据框,如下所示:

import pandas as pd
iterables = [['a', 'b'], ['1', '2']]
my_index = pd.MultiIndex.from_product(iterables, names=['first', 'second'])
df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], columns=my_index)

然后df产生

first  a   b
second 1 2 1 2
0      1 2 3 4
1      5 6 7 8

现在,如果我想要 df['a'] 与其自身的自相关,那很简单:df['a'].corr() 得到了我。请注意,这种相关性的形状为 (2, 2).

我想做的是计算df['a']df['b']的相关矩阵。据推测,代码 df['a'].corrwith(df['b']) 应该给我这个。此代码执行 运行,但结果的形状为 (2,),这对我来说不正确。为什么 .corr() 给出的自相关矩阵给出的结果与 .corrwith() 给出的相关性形状不同?我需要一个与 df['a'].corr() 形状相同的相关矩阵,因为我想绘制 Seaborn 热图,并且我需要 2D 相关矩阵。

提前感谢您的宝贵时间!

您想使用 DataFrame 中的 corr() 函数,而不是系列中的。

看起来像:

In [1]:
# Create the Dataframe
import pandas as pd
iterables = [['a', 'b'], ['1', '2']]
my_index = pd.MultiIndex.from_product(iterables, names=['first', 'second'])
df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], columns=my_index)
df

Out [1]:
first     a       b
second  1   2   1   2
0       1   2   3   4
1       5   6   7   8
In [2]:
## Get the correlation matrix
df.corr()

Out [2]:
        first     a           b
        second  1   2       1   2
first   second              
a          1    1.0 1.0     1.0 1.0
           2    1.0 1.0     1.0 1.0
b          1    1.0 1.0     1.0 1.0
           2    1.0 1.0     1.0 1.0

编辑

Documentation

*可以选择后面的函数 方法 : {‘pearson’, ‘kendall’, ‘spearman’} 或 callable

皮尔逊:标准相关系数

kendall : Kendall Tau相关系数 斯皮尔曼:斯皮尔曼等级相关

可调用:可通过输入两个 1d ndarrays 调用*

这个问题的关键是要认识到 .corr() DataFrame 函数的结果本身就是一个 pandas DataFrame。如果我们运行问题中的代码,然后使用.loc函数,我们可以得到相关矩阵的一个子集。 df.corr()的结果是

        first   a           b
        second  1   2       1   2
first   second              
a          1    1.0 1.0     1.0 1.0
           2    1.0 1.0     1.0 1.0
b          1    1.0 1.0     1.0 1.0
           2    1.0 1.0     1.0 1.0

df.corr().loc['a', 'b']的结果是

second  1    2
second          
1       1.0  1.0
2       1.0  1.0

这就是我想要的。