如何使用CSV文件数据创建图形? [英] How to create a graph using a CSV File data?

查看:285
本文介绍了如何使用CSV文件数据创建图形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在CSV文件中有以下数据,

I have the following data in CSV file,

A,B,50
A,C,34
C,D,55
D,D,80
A,D,90
B,D,78

现在,我想创建一个以A,B,C,D为节点,第三列号为边的图形.我正在使用networkx库.第三列编号显示A,B和A,C等共享的公用项目.

Now I want to create a graph with A, B, C, D as nodes and the third column numbers as edges. I am using networkx library. The third column number shows the common items shared by A,B and A,C and so on.

我打开并阅读csv文件.

I open and read the csv file.

Graphs = nx.Graph()

for row in openedfile:
 Graphs.add_node(row[0])
 Graphs.add_edge(row[2])

nx.draw_graphviz(Graphs)

上面的代码给我一个错误.我无法得到正确的答案.

The above code gives me an error. I am not able to get the right answer.

推荐答案

我不确定我是否了解您的文件格式,因为前两列似乎告诉您应通过边缘连接的节点第三列是该边缘的权重.

I'm not sure I understand the format of your file, in that it seems like the first two columns tell you the nodes that should be connected by an edge and the third column is the weight of that edge.

假设是这种情况,将边缘的CSV文件加载到NetworkX中的一种更简单的方法是使用的文件中):

Assuming that is the case, a simpler way to load a CSV file of edges into NetworkX is to use the networkx.read_edgelist function. Here's an example for your graph (assuming it's stored in a file named "edges.txt"):

In [1]: import networkx as nx
In [2]: G = nx.read_edgelist("edges.txt", delimiter=",", data=[("weight", int)]) 
In [3]: G.edges(data=True)
Out[1]: 
[(u'A', u'C', {'weight': 34}),
 (u'A', u'B', {'weight': 50}),
 (u'A', u'D', {'weight': 90}),
 (u'C', u'D', {'weight': 55}),
 (u'B', u'D', {'weight': 78}),
 (u'D', u'D', {'weight': 80})]

要注意的重要参数是,您需要将每行的定界符设置为逗号(","),并且需要指定存储在第三列中的数据是整数,应使用键"weight".

The important parameters to note are that you need to set the delimiter for each row to a comma (","), and you need to specify that the data stored in the third column is an integer that should be stored using the key "weight".

然后可以使用权重作为边缘标签绘制图形,如下所示:

You can then draw your graph with the weights as edge labels as follows:

In [4]: edge_labels = dict( ((u, v), d["weight"]) for u, v, d in G.edges(data=True) )
In [5]: pos = nx.random_layout(G)
In [6]: nx.draw(G, pos)
In [7]: nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
In [8]: import matplotlib.pyplot as plt; plt.show()

这篇关于如何使用CSV文件数据创建图形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆