Creating a network where nodes store multiple attribute data with networkx

Viewed 52

I have a dataframe as below:

enter image description here

and would like to create a network where nodes are from the con.taxonomy and res.taxonomy columns, the edges being created via geographic.location. I have managed to create the network, as follows:

G = nx.from_pandas_edgelist(swiz_lakes, "con.taxonomy", "res.taxonomy", "geographic.location")

however, I was wondering whether it was possible to add other attributes to the nodes, as it is possible to do via the edges. E.g. I could have

G = nx.from_pandas_edgelist(swiss_lakes, "con.taxonomy", "res.taxonomy", ["geographic.location", "con.metabolic.type", "con.movement.type", "res.metabolic.type", "res.movement.type"])

I want to know if something similar can be done so as to store further information in the nodes, but not as labels.

Is this possible, or if not, please could somebody explain why not?

1 Answers

Of course this is possible. In my opinion the easiest way to achieve this would be to create a dict of the nodes and the relevant information and use nx.set_node_attributes.

Convert your dataframe in a dict of dicts, where the first level keys are your node names and second level keys are your attribute names, and the values are the corresponding values from your dataframe. (Probably it is easiest to use: your_dict = df.to_dict(orient="your_node_name_colum")) and then use nx.set_node_attributes(G, your_dict).

Check out the networkx documentation: https://networkx.org/documentation/stable/reference/generated/networkx.classes.function.set_node_attributes.html

Related