LdM
LdM

Reputation: 704

Adding new nodes to an existing network

I have a network (built using networkx) which takes into consideration the following aspects:

As an example, you could refer to the below:

import networkx as nx
import pandas as pd

edges_df = pd.DataFrame({
    'Node': ['A', 'A', 'B', 'B', 'B', 'S'],
    'Edge': ['B', 'D', 'N', 'A', 'X', 'C']
})

attributes_df = pd.DataFrame({
    'Node': ['A', 'B', 'C', 'D', 'N', 'S', 'X'],
    'Attribute': [-1, 0, -1.5, 1, 1, 1.5, 0]
})

G = nx.from_pandas_edgelist(edges_df, source='Node', target='Edge')

mapper = {-1.5: 'grey', -1: 'red', 0: 'orange', 1: 'yellow', 1.5: 'green'}
colour_map = (
attributes_df.set_index('Node')['Attribute'].map(mapper)
    .reindex(G.nodes(), fill_value='black')
)

# Add Attribute to each node
nx.set_node_attributes(G, colour_map, name="colour")

# Then draw with colours based on attribute values:
nx.draw(G, 
        node_color=nx.get_node_attributes(G, 'colour').values(),
        with_labels=True)

I would like to add one or more nodes to the existing network. These new nodes have information on the neighbor links but not generally on the attribute (they might not be in the attributes dataset).

new_df = pd.DataFrame({
    'Node': ['A','D', 'X', 'X', 'Z', 'Z'],
    'Edge': ['B', 'B', 'N', 'N', 'A', 'F']
})

Can you please explain to me how to add these new nodes to my existing network? If they are in the attributes_df, they should also be colored accordingly. Otherwise, they should be black.

Upvotes: 0

Views: 216

Answers (1)

Frodnar
Frodnar

Reputation: 2242

The G.add_edges_from() method requires doesn't support a "two-column" format like nx.from_pandas_edgelist() does. So you just need to reshape your new_df data by zip-ing the columns together.

Then call your definition of colour_map again to fill in the black values, set the node attributes again, and finally draw.

G.add_edges_from(zip(new_df.Node, new_df.Edge))

colour_map = attributes_df.set_index('Node')['Attribute'].map(mapper).reindex(G.nodes(), fill_value='black')

nx.set_node_attributes(G, colour_map, name="colour")
nx.draw(G, 
        node_color=nx.get_node_attributes(G, 'colour').values(),
        with_labels=True)

Upvotes: 1

Related Questions