networkx node attribute from a dataframe

Solutions on MaxInterview for networkx node attribute from a dataframe by the best coders in the world

showing results for - "networkx node attribute from a dataframe"
Caterina
12 Jul 2020
1import networkx as nx
2import pandas as pd
3
4# Build a sample dataframe (with 2 edges: 0 -> 1, 0 -> 2, node 0 has attr_1 value of 'a', node 1 has 'b', node 2 has 'c')
5d = {'node_from': [0, 0], 'node_to': [1, 2], 'src_attr_1': ['a','a'], 'tgt_attr_1': ['b', 'c']}
6df = pd.DataFrame(data=d)
7G = nx.from_pandas_edgelist(df, 'node_from', 'node_to')
8
9# Iterate over df rows and set the source and target nodes' attributes for each row:
10for index, row in df.iterrows():
11    G.nodes[row['node_from']]['attr_1'] = row['src_attr_1']
12    G.nodes[row['node_to']]['attr_1'] = row['tgt_attr_1']
13
14print(G.edges())
15print(G.nodes(data=True))