yadi shahryary - 1 year ago 112

Python Question

I'm trying to create a graph with graph-tool (https://graph-tool.skewed.de) from csv file that content like:

`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 graph-tool library. The third column number shows the common items shared by A,B and A,C and so on.

I can do it by "networkx" (read_edgelist and etc) but I want to do it with graph-tool.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Assuming you already know how to read the CSV file in Python (for example, using the CSV library), The docs on the website explain how to do this very clearly.

Something like

```
import graph_tool
g = Graph(directed=False)
# this is the result of csv.parse(file)
list_of_edges = [['A', 'B', 50], ['A','C',34], ['C','D',55], ['D','D',80], ['A','D',90], ['B','D',78]]
vertices = {}
for e in list_of_edges:
if e[0] not in vertices:
vertices[e[0]] = True
if e[1] not in vertices:
vertices[e[1]] = True
for d in vertices:
vertices[d] = g.add_vertex()
for edge in list_of_edges:
g.add_edge(vertices[edge[0]], vertices[edge[1]])
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**