简体   繁体   中英

How to create a graph using a CSV File data?

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

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.

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.

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})]

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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