'Creating a simple graph using pandas and Networkx

I am trying to figure out from the documentation how to create a simple graph using the pandas dataframe and the NetworkX package, but I couldn't get the solution. Below the final result I would like.

Desired solution



Solution 1:[1]

This might help:

import pandas as pd
import networkx as nx


df = pd.DataFrame(
    {"from": ["A", "A", "A", "C"], "to": ["B", "C", "D", "D"], "weight": [10, 5, 4, 1]}
)


G = nx.from_pandas_edgelist(
    df, source="from", target="to", edge_attr=["weight"], create_using=nx.DiGraph
)
pos = nx.spring_layout(G)  # node positions

edge_labels = nx.get_edge_attributes(G, "weight") # labels to use for edges

nx.draw(G, pos, with_labels=True)
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)

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