Here is basically the same answer, but updated with some details filled out. We will start with basically the same setup, but there will be no indexes for the nodes, only the names for the @LancelotHolmes address of the comment and we will make it more general:
import networkx as nx import pandas as pd linkData = pd.DataFrame({'source' : ['Amy', 'Bob'], 'target' : ['Bob', 'Cindy'], 'weight' : [100, 50]}) nodeData = pd.DataFrame({'name' : ['Amy', 'Bob', 'Cindy'], 'type' : ['Foo', 'Bar', 'Baz'], 'gender' : ['M', 'F', 'M']}) G = nx.from_pandas_edgelist(linkData, 'source', 'target', True, nx.DiGraph())
Here, the True
parameter tells NetworkX to save all properties in linkData as link properties. In this case, I made it a DiGraph
type, but if you do not need it, you can make it another type in the obvious way.
Now, since you need to map nodeData by the name of the nodes generated from linkData, you need to set the dataframe index for nodeData as the name
property before you make it a dictionary so NetworkX 2.x can load it. as node attributes.
nx.set_node_attributes(G, nodeData.set_index('name').to_dict('index'))
This loads the entire nodeData data frame into a dictionary in which the key is the name, and the rest of the properties are key: value pairs in this key (i.e., the Normal properties of the node, where the node index is its name).