Search code examples
graphnetworkx

add a second edge's attribute into a existing graph


I'm trying to add a second edge's attribute in a existing graph.

I created a graph G and save it as a pkl file.

edges1 = pd.DataFrame({'source':[0,1,2,3,4],
                        'target':[10,11,12,13,14],
                        'weight':[50,50,50,50,50]})
G = nx.from_pandas_edgelist(edges1, 'source', 'target', 'weight')

I loaded G and then tried to add the second edge's attribute(cost) and a node attribute. But it keeps overwriting the first edges' attribute(weight).

edges2 = pd.DataFrame({'source':[0,1,2,6,7,8],
                        'target':[10,11,12,16,17,18],
                        'cost':[100,100,100,100,100,100]})

nodes = pd.DataFrame({'node':[0,1,2,3,10,18],
                      'name':['A','B','C','D','E','F']})
nx.from_pandas_edgelist(edges2, 'source', 'target', 'cost')
nx.set_node_attributes(G, pd.Series(nodes.name, index=nodes.node).to_dict(), 'name')

I must load the graph G, so combining edges1 and edges2 DataFrames and creating a graph isn't what I need.

How can I get this?

[(0, 10, {'weight':50, 'cost': 100}), (1, 11, {'weight':50, 'cost': 100}) ...]

instead of this

[(0, 10, {'cost': 100}), (1, 11, {'cost': 100}) ...]


Solution

  • I'm not clear if you want to add new edges from edges2 or not. If you are okay with adding new edges, you can use nx.compose:

    H = nx.from_pandas_edgelist(edges2, 'source', 'target', 'cost')
    G_updated = nx.compose(G, H)
    

    If you don't want to add new edges, then you can check if the edge exists and then set the edge attribute directly:

    H = nx.from_pandas_edgelist(edges2, 'source', 'target', 'cost')
    for edge in H.edges():
        if edge in G.edges():
            G.edges[edge]['cost'] = H.edges[edge]['cost']
    

    If performance is an issue, you could also consider setting the edge attributes of G directly by using your edges2 data without building a second graph or even a second dataframe.