I am trying to make a graph for this data using the following code:
import networkx as nx
import csv
import matplotlib.pyplot as plt
graph = nx.Graph()
filename = "tubedata.csv"
with open(filename) as tube_data:
starting_station = [row[0] for row in csv.reader(tube_data, delimiter=',')]
with open(filename) as tube_data:
ending_station = [row[1] for row in csv.reader(tube_data, delimiter=',')]
with open(filename) as tube_data:
average_time_taken = [row[3] for row in csv.reader(tube_data, delimiter=',')]
with open(filename) as tube_data:
for line in tube_data:
graph.add_edge(starting_station, ending_station, weight=average_time_taken)
However, I keep getting the following error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/tmp/ipykernel_101/53822893.py in <module>
17 with open(filename) as tube_data:
18 for line in tube_data:
---> 19 graph.add_edge(starting_station, ending_station, weight=average_time_taken)
/opt/conda/lib/python3.9/site-packages/networkx/classes/graph.py in add_edge(self, u_of_edge, v_of_edge, **attr)
870 u, v = u_of_edge, v_of_edge
871 # add nodes
--> 872 if u not in self._node:
873 self._adj[u] = self.adjlist_inner_dict_factory()
874 self._node[u] = self.node_attr_dict_factory()
TypeError: unhashable type: 'list'
I have searched the error and understand that I need to pass a data structure that is immutable. I changed the code to the following:
with open(filename) as tube_data:
starting_station = (row[0] for row in csv.reader(tube_data, delimiter=','))
with open(filename) as tube_data:
ending_station = (row[1] for row in csv.reader(tube_data, delimiter=','))
with open(filename) as tube_data:
average_time_taken = (row[3] for row in csv.reader(tube_data, delimiter=','))
with open(filename) as tube_data:
for line in tube_data:
graph.add_edge(starting_station, ending_station, weight=average_time_taken)
This resolves the above error but produces a graph with only two nodes and 1 edge? How can I capture the full data as a graph?