How to add/set node attributes to grid_2d_graph from numpy array/Pandas dataFrame

10 views
Skip to first unread message

Cheng Xi Chen

unread,
Jul 14, 2022, 4:53:46 PMJul 14
to networkx-discuss
Hi, 

A graph is created by grid_2d_graph (G = nx.grid_2d_graph(3,3)).
I am wondering how to add node attributes to this graph. For example, there are 5 features for each node.

I am not sure how to use set_node_attributes.

Thanks!

Regards,
-cheng xi

Dan Schult

unread,
Jul 14, 2022, 10:14:53 PMJul 14
to networkx...@googlegroups.com
The docs for networkx.set_node_attributes are at https://networkx.org/documentation/stable/index.html
It says that the "value" needs to be a dict-like structure keyed by node to the value of the attribute.
Call the function once for each attribute and provide a dict  like `{node: color(node) for node in G}`.

Or, if it is more convenient, don't use set_node_attributes.  Instead, loop over the nodes and add all five
attributes for each node:
for node in G:
    G.nodes[node]["color"] = color_func(node)
    G.nodes[node]["size"] = size_func(node)
    ...

There are other good ways to input node attributes that might work better depending on how those attributes are stored ahead of time. For example, if they are in a pandas data frame you can use df.to_dict().

Cheng Xi Chen

unread,
Jul 15, 2022, 11:14:22 PMJul 15
to networkx-discuss
Hi,

df.to_dict() solved my problem.

Thanks!

Regards,
-cheng xi

Reply all
Reply to author
Forward
0 new messages