Create the weighted graph from the edge table using nx.from_pandas_dataframe
:
import networkx as nx
import pandas as pd
edges = pd.DataFrame({'source' : [0, 1],
'target' : [1, 2],
'weight' : [100, 50]})
nodes = pd.DataFrame({'node' : [0, 1, 2],
'name' : ['Foo', 'Bar', 'Baz'],
'gender' : ['M', 'F', 'M']})
G = nx.from_pandas_dataframe(edges, 'source', 'target', 'weight')
Then add the node attributes from dictionaries using set_node_attributes
:
nx.set_node_attributes(G, 'name', pd.Series(nodes.name, index=nodes.node).to_dict())
nx.set_node_attributes(G, 'gender', pd.Series(nodes.gender, index=nodes.node).to_dict())
Or iterate over the graph to add the node attributes:
for i in sorted(G.nodes()):
G.node[i]['name'] = nodes.name[i]
G.node[i]['gender'] = nodes.gender[i]
Update:
As of nx 2.0
the argument order of nx.set_node_attributes
has changed: (G, values, name=None)
Using the example from above:
nx.set_node_attributes(G, pd.Series(nodes.gender, index=nodes.node).to_dict(), 'gender')
And as of nx 2.4
, G.node[]
is replaced by G.nodes[]
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…