Reputation: 89
Given two DataFrames, one for Nodes and another for Edges. How can I get those into a networkx graph including the attribute columns I have?
Example:
df_nodes
ID | Label | Attribute_W | Attribute_X | |
---|---|---|---|---|
0 | 0 | Japan | Asia | 81 |
1 | 1 | Mexico | America | 52 |
2 | 2 | Ireland | Europe | 353 |
df_Edges
Target | Source | Attribute_Y | Attribute_Z | |
---|---|---|---|---|
0 | 0 | 1 | 10 | 1 |
1 | 0 | 2 | 15 | 2 |
2 | 1 | 2 | 20 | 3 |
I tried with G = nx.from_pandas_edgelist but it returns an attribute error. And I'm not sure of how to add the attributes in the construction of the graph.
I'm looking to output a graphml file nx.write_graphml(G, "My_File.graphml")
Thanks.
Upvotes: 1
Views: 455
Reputation: 76
I too do not see any way how to include node attributes via from_pandas_edgelist. However, you can achieve what you want just using nx.add_edges_from and nx.add_nodes_from in a few lines of code.
G = nx.Graph()
node_label_attr = "Label"
for index,row in df_nodes.iterrows():
as_dict = row.to_dict()
label = as_dict[node_label_attr]
del as_dict[node_label_attr]
G.add_nodes_from([(label, as_dict)])
for index,row in df_Edges.iterrows():
as_dict = row.to_dict()
source = as_dict["Source"]
target = as_dict["Target"]
del as_dict["Source"]
del as_dict["Target"]
G.add_edges_from([(source,target,as_dict)])
You iterate through the rows of the dataframe and convert them to dictionaries which are understood by nx.add_nodes_from and nx.add_edges_from.
Upvotes: 2