I created a graph G (network library) through the adjacency matrix A (numpy matrix) that stores the weights of the links.
import numpy as np import networkx as nx A = np.loadtxt('SM_waste.csv',delimiter=';') G = nx.from_numpy_matrix(A, parallel_edges=False, create_using=None)
I also have the list of the names of the nodes but I don’t know how to assign the name to each node. How can I do?
Advertisement
Answer
You can loop over the nodes and append the label from the row index.
Example with faker data:
import faker import networkx as nx for node in G.nodes(): G.nodes[node]['name'] = faker.Faker().name() G.nodes(data=True)
With some fake names this outputs for ten nodes a NodeDataView looking like so
>>> NodeDataView({0: {'name': 'Kayla Martin'}, 1: {'name': 'Billy Knight'}, 2: {'name': 'Joshua Landry'}, 3: {'name': 'Jessica Perez'}, 4: {'name': 'Emily Garcia'}, 5: {'name': 'Stephen Foster'}, 6: {'name': 'Timothy Howell'}, 7: {'name': 'Stephanie Gonzales'}, 8: {'name': 'Maurice Miller'}, 9: {'name': 'Emily Caldwell'}, 10: {'name': 'Amy Rice'}
In your case this could look something like:
import numpy as np import networkx as nx A = np.loadtxt('SM_waste.csv',delimiter=';') G = nx.from_numpy_matrix(A, parallel_edges=False, create_using=None) labels = ["<list of your row labels here indexed according to the adjacency matrix>"] for idx, node in enumerate(G.nodes()): G.nodes[node]['label'] = labels[idx]
Note that the above solution probably won’t work if you call G.nodes()
with data=True
.
Hope this helps.