简体   繁体   English

Networkx:从Pandas DataFrame中的距离矩阵绘制网络

[英]Networkx: Draw Network from Distance Matrix in Pandas DataFrame from

I have a cosine distance matrix as a pandas dataframe. 我有一个余弦距离矩阵作为熊猫数据框。 I can visualise it as a network if I convert it to a numpy matrix and do the following: 如果将其转换为numpy矩阵并执行以下操作,则可以将其可视化为网络:

DistMatrix = cosine1
G = G=nx.from_numpy_matrix(DistMatrix)
nx.draw(G , with_labels=True)
plt.show()

The problem is that I loose the labels of my nodes. 问题是我松开了节点的标签。 These labels were in the pandas dataframe however. 这些标签在大熊猫数据框中。 Being a distance matrix, the column labels are of course the same as the index labels and the diagonal of the matrix has entries which are 0 (they are exactly the same). 作为距离矩阵,列标签当然与索引标签相同,并且矩阵的对角线条目为0(它们完全相同)。

How would I draw a network from my pandas dataframe and include the labels to label the nodes correctly? 如何从熊猫数据框中绘制网络并包含标签以正确标记节点?

 DistMatrix = pd.DataFrame( data = cosine , index = label_list , columns = label_list)

Is it maybe possible to just add labels to the numpy matrix version? 是否可以仅将标签添加到numpy矩阵版本?

You can add labels manually with the function relabel_nodes by adding a dictionary with the mapping of the numbering to the labels. 您可以使用功能relabel_nodes手动添加标签,方法是添加带有编号到标签的映射的字典。

G = nx.from_numpy_matrix(DistMatrix.values)

labels = DistMatrix.columns.values
G = nx.relabel_nodes(G, dict(zip(range(len(labels)), labels)))

nx.draw(G, with_labels=True)
plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM