Networkx: create weighted graph from pandas

Viewed 21

I am trying to create a weighted graph in networkx, but am facing problems when indicating the weight. My code

import pandas as pd
import networkx as nx
dictt = {"from" :["A", "B", "C"], "to":["B", "D", "A"],}
distmat = pd.DataFrame.from_dict(dictt)
distmat["weight"] = [1, 2, 4]
d = distmat.to_numpy()
data = list(map(tuple, d))
G = nx.Graph()
G.add_edges_from(data, weight = "weight")

returns TypeError: 'int' object is not iterable. Any ideas on how to solve the issue?

1 Answers

Was using the wrong networkx function, here the correct code:

dictt = { "from": ["A", "B", "C"], "to": ["B", "D", "A"]}
distmat = pd.DataFrame.from_dict(dictt)
distmat["weight"] = [1, 2, 4]
d = distmat.to_numpy()
data = list(map(tuple, d))
G = nx.Graph()
G.add_weighted_edges_from(data, weight = "weight")
Related