'How can I create network graph from dataframe

I have dataframe like this table below:

source destination weight
A B 0.5
A C 0.2
B C 0.1
B D 0.1
C D 0.1

How can I create network graph by source to destination and show number of weight on edge?



Solution 1:[1]

import networkx as nx
import pandas as pd

data = {'source':["A", "A", "B", "B", "C"],
        'destination':["B", "C", "C", "D", "D"],
        'weight':[0.5, 0.2, 0.1, 0.1, 0.1]}

df = pd.DataFrame(data)

g = nx.Graph()

weighted_edges = list(zip(*[df[col] for col in df]))

g.add_weighted_edges_from(weighted_edges)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 IDK