创建非冗余相关矩阵 Python 的最有效方法?

Most efficient way to create non-redundant correlation matrix Python?

我觉得 numpy、scipy 或 networkx 有一种方法可以做到这一点,但我还没有弄清楚。

我的问题是如何以最有效的方式(在 Python 中)从大型数据集的冗余相关矩阵创建 DataFrame 形式的非冗余相关矩阵? =31=]

我在 7000x7000 矩阵上使用这种方法,它在我的 MacBook Air 4GB Ram 上花费了很长时间(我知道,我绝对不应该用它来编程,但那是另一个讨论)

冗余相关矩阵示例

非冗余相关矩阵示例

我在下面给出了一种非常幼稚的方法,但必须有更好的方法。我喜欢将我的矩阵存储在稀疏矩阵中并将它们转换为数据帧以供存储。

import pandas as pd
import numpy as np
import networkx as nx

#Example DataFrame
L_test = [[0.999999999999999,
  0.374449352805868,
  0.000347439531148995,
  0.00103026903356954,
  0.0011830950375467401],
 [0.374449352805868,
  1.0,
  1.17392596672424e-05,
  1.49428208843456e-07,
  1.216664263989e-06],
 [0.000347439531148995,
  1.17392596672424e-05,
  1.0,
  0.17452569907144502,
  0.238497202355299],
 [0.00103026903356954,
  1.49428208843456e-07,
  0.17452569907144502,
  1.0,
  0.7557000865939779],
 [0.0011830950375467401,
  1.216664263989e-06,
  0.238497202355299,
  0.7557000865939779,
  1.0]]
labels = ['AF001', 'AF002', 'AF003', 'AF004', 'AF005']
DF_1 = pd.DataFrame(L_test,columns=labels,index=labels)

#Create Nonredundant Similarity Matrix
n,m = DF_test.shape #they will be the same since it's adjacency
#Empty array to fill
A_tmp = np.zeros((n,m)) 
#Copy part of the array
for i in range(n):
    for j in range(m):
        A_tmp[i,j] = DF_test.iloc[i,j]
        if j==i:
            break
#Make array sparse for storage
A_csr = csr_matrix(A_tmp) 
#Recreate DataFrame
DF_2 = pd.DataFrame(A_csr.todense(),columns=DF_test.columns,index=DF_test.index) 
DF_2.head()

我认为您可以使用 np.tril 创建数组,然后使用 DataFrame 对其进行倍增 DF_1:

print np.tril(np.ones(DF_1.shape))
[[ 1.  0.  0.  0.  0.]
 [ 1.  1.  0.  0.  0.]
 [ 1.  1.  1.  0.  0.]
 [ 1.  1.  1.  1.  0.]
 [ 1.  1.  1.  1.  1.]]

print np.tril(np.ones(DF_1.shape)) * DF_1
          AF001         AF002     AF003   AF004  AF005
AF001  1.000000  0.000000e+00  0.000000  0.0000      0
AF002  0.374449  1.000000e+00  0.000000  0.0000      0
AF003  0.000347  1.173926e-05  1.000000  0.0000      0
AF004  0.001030  1.494282e-07  0.174526  1.0000      0
AF005  0.001183  1.216664e-06  0.238497  0.7557      1