从对列表中制作 Numpy 对称矩阵

我有一个相关矩阵,但指定为对,例如:


cm = pd.DataFrame({'name1': ['A', 'A', 'B'], 

                   'name2': ['B', 'C', 'C'], 

                   'corr': [0.1, 0.2, 0.3]})

cm

    name1   name2   corr

0   A       B       0.1

1   A       C       0.2

2   B       C       0.3

将其转换为 numpy 二维数组相关矩阵的最简单方法是什么?


    A   B   C

A 1.0 0.1 0.2

B 0.1 1.0 0.3

C 0.2 0.3 1.0


元芳怎么了
浏览 194回答 3
3回答

慕的地8271018

不确定,pure numpy因为您正在处理熊猫数据框。这是一个纯粹的熊猫解决方案:s = cm.pivot(*cm)ret = s.add(s.T, fill_value=0).fillna(1)输出:     A    B    CA  1.0  0.1  0.2B  0.1  1.0  0.3C  0.2  0.3  1.0额外:反向(ret如上)(ret.where(np.triu(np.ones(ret.shape, dtype=bool),1))    .stack()    .reset_index(name='corr'))输出:  level_0 level_1  corr0       A       B   0.11       A       C   0.22       B       C   0.3import networkx as nxG = nx.from_pandas_edgelist(cm.rename(columns={'corr':'weight'}),                             source='name1',                             target='name2',                             edge_attr ='weight')G.edges(data=True)# EdgeDataView([('A', 'B', {'weight': 0.1}), ('A', 'C', {'weight': 0.2}), #               ('B', 'C', {'weight': 0.3})])adj = nx.to_pandas_adjacency(G)# sets the diagonal to 1 (node can't be connected to itself)adj[:] = adj.values + np.eye(adj.shape[0])print(adj)    A    B    CA  1.0  0.1  0.2B  0.1  1.0  0.3C  0.2  0.3  1.0

郎朗坤

一种方法是使用 构建图networkX,将corr列设置为边,并使用weight获取邻接矩阵nx.to_pandas_adjacency:

斯蒂芬大帝

鉴于最后一列以适当的方式排序,我们可以使用以下代码。import pandas as pdimport numpy as np# define data framedata = pd.DataFrame({&nbsp; &nbsp; 'name1': ['A', 'A', 'B'],&nbsp; &nbsp; 'name2': ['B', 'C', 'C'],&nbsp; &nbsp; 'correlation': [0.1, 0.2, 0.3]})# get correlation column and dimensioncorrelation = data['correlation'].valuesdimension = correlation.shape[0]# define empty matrix to fill and unit matrixmatrix_upper_triangular = np.zeros((dimension, dimension))# fill upper triangular matrix with one half at diagonalcounter = 0for (row, column), element in np.ndenumerate(matrix_upper_triangular):&nbsp; &nbsp; # half of diagonal terms&nbsp; &nbsp; if row == column:&nbsp; &nbsp; &nbsp; &nbsp; matrix_upper_triangular[row, column] = 0.5&nbsp; &nbsp; # upper triangular values&nbsp; &nbsp; elif row < column:&nbsp; &nbsp; &nbsp; &nbsp; matrix_upper_triangular[row, column] = correlation[counter]&nbsp; &nbsp; &nbsp; &nbsp; counter = counter + 1&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; pass# add upper triangular + lower triangular matrixcorrelation_matrix = matrix_upper_triangularcorrelation_matrix += matrix_upper_triangular.transpose()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python