Kenneth Leung
Dec 9, 2022

--

Hi Yin, in your DataFrame with the target and source, you can specify an additional column with the weights.

Something like:

df = pd.DataFrame({'source': ['A', 'A', 'B', 'B'],

'target': ['B', 'C', 'A', 'C'],

'weight': [1, 2, 3, 4]})

And then you can pass the weight column name into the `edge_attr` parameter of the nx.from_pandas_edgelist function:

G = nx.from_pandas_edgelist(df, 'source', 'target', edge_attr='weight').

In the NetworkX object, you can run the following loop to view the weight for each edge:

for i, j, weight in G.edges(data='weight'):

print(f'({i}, {j}) weight: {weight}')

--

--

Kenneth Leung
Kenneth Leung

Written by Kenneth Leung

Senior Data Scientist at Boston Consulting Group | Top Tech Author | 2M+ reads on Medium | linkedin.com/in/kennethleungty | github.com/kennethleungty

Responses (1)