使用
我有一个 4300*4300 对角对称的大熊猫数据帧,其中 1 作为对角线值。 它是一个相关矩阵。我想读取此矩阵的一半以及与该值关联的相应 2 列名称。
我已经编写了 2 个嵌套的循环,将值和列名称读取到 3 个列表中, 但这需要很长时间。有没有有效的方法。
预期输出数据帧:
column1, column2, corr_val
设置
生成相关矩阵
np.random.seed([3, 1415])
df = pd.DataFrame(np.random.rand(10, 5), columns=list('ABCDE')).corr()
df
A B C D E
A 1.000000 0.309111 0.219242 -0.239779 0.253331
B 0.309111 1.000000 0.435033 0.475270 0.881688
C 0.219242 0.435033 1.000000 0.005637 0.394912
D -0.239779 0.475270 0.005637 1.000000 0.483238
E 0.253331 0.881688 0.394912 0.483238 1.000000
使用np.triu_indices
i, j = np.triu_indices_from(df, k=1)
d = pd.DataFrame(dict(
ROW=df.index[i],
COL=df.columns[j],
VAL=df.values[i, j]
))
d
COL ROW VAL
0 B A 0.309111
1 C A 0.219242
2 D A -0.239779
3 E A 0.253331
4 C B 0.435033
5 D B 0.475270
6 E B 0.881688
7 D C 0.005637
8 E C 0.394912
9 E D 0.483238