如何从 pandas df 相关性中获取元素数量

how to get number of elements from pandas df correlation

我有:

df=pd.DataFrame({'A':[1,2,3,np.NaN,435,546],
             'B':[10,2,3,4,867,23],
             'C':[4,5,np.NaN, np.NaN,np.NaN,64]})
df


    A       B   C
0   1.0     10  4.0
1   2.0     2   5.0
2   3.0     3   NaN
3   NaN     4   NaN
4   435.0   867 NaN
5   546.0   23  64.0

我用 df.corr() 计算相关性,这是 returns 相关矩阵。根据文档,correlation 删除了 NaN,这在计算 correlation(A,B) 时有 5 个值可供选择,而 correlation(A,C) 有 3 个值。

我运行这是根据每个配对获取元素的数量。

for i in range(df.shape[1]):
  for j in range(df.shape[1]):
    if j==i: continue
    print(df.columns[i],df.columns[j],df.iloc[:,np.r_[i,j]].dropna().shape)
A B (5, 2)
A C (3, 2)
B A (5, 2)
B C (3, 2)
C A (3, 2)
C B (3, 2)

我怎样才能 运行 形成它,以便我可以在与使用 df.corr()

的矩阵类似的矩阵中得到它
    A           B           C
A   1.000000    0.508726    0.999916
B   0.508726    1.000000    0.920458
C   0.999916    0.920458    1.000000

你要找的是普通非nan的数量:

s = df.notna().astype(int)

s.T @ s

输出:

   A  B  C
A  5  5  3
B  5  6  3
C  3  3  3