Reputation: 39
What I am trying to do is build a graph in NetworkX, in which every node is a train station. To build the nodes I did:
G = nx.Graph()
G.add_nodes_from(trains['Stopping place'].unique())
which (at least as it looks like) it's working.
Now, since for each line I have the stops in sequence, I built my paths like so:
stops_by_line = ((belgium_trains.sort_values(['Train number','Actual arrival datetime']).groupby('Train number'))['Stopping place'].apply(list).to_dict())
paths = ([tuple(val) for val in stops_by_line.values()])
and the variable looks like this:
[('HERGENRATH',
'CHENEE',
'ANGLEUR',
'LIEGE-GUILLEMINS',
'ANS',
'LEUVEN',
'HERENT',
'VELTEM',
'ERPS-KWERPS',
'KORTENBERG',
'NOSSEGEM',
'ZAVENTEM',
'DIEGEM',
'HAREN-ZUID',
'SCHAARBEEK',
'BRUSSEL-NOORD',
'BRUSSEL-CONGRES',
'BRUSSEL-CENTRAAL',
'BRUSSEL-KAPELLEKERK',
'BRUSSEL-ZUID'),
(...other ordered tuples of stops),...)]
Now my question is, since all of these elements are also node names, how can I build the edges using these tuples sequentially (for example add an edge between BRUSSEL-NOORD and BRUSSEL-CONGRES, then from BRUSSEL-CONGRES to BRUSSEL-CENTRAAL and so on)?
Upvotes: 1
Views: 1241
Reputation: 4892
You can simply use the add_path
method in a loop:
for path in paths:
nx.add_path(G, path)
Sidemark, if you add an edge (like e.g. above), then networkx
also directly adds the respective nodes to the graph. So probably (if all stops are covered by some train) you don't need to add the nodes manually before.
Upvotes: 1