1

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.