Search code examples
pythonpandasgraphnetworkxgraph-visualization

adding weight list to already created edgelist from pandas dataframe and display the weight as a edge label in graph


I have my data in pandas dataframe, it has source, target , weight.

H=nx.from_pandas_edgelist(links,source='source',target='target')

used this to create my edge list, this doesnt have an option to add weights, i have also kept my data in different forms apart from pd.DataFrame

edges_df={'source':links['source'], 'target':links['target'], 'weights':links['value']} edges_source=links['source']
edges_target=links['target'] weights=links['value']

same thing but different structure , i tried using nx.set_edge_attribute but it gave an error along the lines of not iterable/hashable , not in the G[u][v][w]


Solution

  • The simple thing would be to use the edge_attr parameter when creating your graph like below.

    H=nx.from_pandas_edgelist(links,source='source',target='target',edge_attr='weight')
    

    If you already created the graph and want to add the attributes after the fact, you can use

    for e in g.edges:
        g.edges[e]['weight'] = df.loc[(df.source == e[0]) & (df.target == e[1]),'weight'].values[0] #use .value[0] to ensure you get the value, not an array or series