i2_
i2_

Reputation: 735

Adding Attributes to Nodes from Dataframe in a Network

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?

Upvotes: 2

Views: 3534

Answers (2)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210982

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})]

Upvotes: 0

Johannes Wachs
Johannes Wachs

Reputation: 1310

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

Upvotes: 2

Related Questions