2

I asked this question before but after a comment I want to change it:

import networkx as nx

What I Have: a graph G imported in networkx from dataframe using by nx.from_pandas_dataframe()

Problem : When I used nx.from_pandas_dataframe(dataframe, 'Sources', 'Target', edge_attr=True) nx thinks all other colums rather then Sources and Target are attributes to edges.

What I want to do: I want to use some columns of dataframe as attributes of nodes.

My Question : Is there any easy way to do this(like edge_attr=True add many attributes with only one function)? If not How can I add many attributes to nodes from a dataframe? For example:

Airline Sources Target  SLongitudeLatitude  TLongitudeLatitude  SPopulation NPopulation
Alpha   A           Z              1               10              101             111
Delta   B           Y              2               11              102             112
Gamma   C           X              3               12              103             113
Omega   D           W              4               13              104             114
Lambda  E           U              5               14              105             115
Zeta    F           T              6               15              106             116
Beta    G           S              7               16              107             117
Phi     H           R              8               17              108             118

Airline Column is attribute to edges but rest of columns (SLongitudeLatitude, TLongitudeLatitude and Population) are attribute for nodes.

Or can I add attributes to nodes from different dataframe?

2 Answers 2

2

Networkx can only take edge attributes from Pandas dataframes, but it isn't too bad to add the node attributes in a separate step, as this answer outlines:

Load nodes with attributes and edges from DataFrame to NetworkX

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

Comments

0

Is that what you want?

G = nx.from_pandas_dataframe(df, 'Sources', 'Target', edge_attr=['NPopulation','SPopulation'])
G.edges(data=True)

Result:

[('A', 'Z', {'NPopulation': 111, 'SPopulation': 101}),
 ('B', 'Y', {'NPopulation': 112, 'SPopulation': 102}),
 ('C', 'X', {'NPopulation': 113, 'SPopulation': 103}),
 ('D', 'W', {'NPopulation': 114, 'SPopulation': 104}),
 ('E', 'U', {'NPopulation': 115, 'SPopulation': 105}),
 ('F', 'T', {'NPopulation': 116, 'SPopulation': 106}),
 ('G', 'S', {'NPopulation': 117, 'SPopulation': 107}),
 ('H', 'R', {'NPopulation': 118, 'SPopulation': 108})]

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.