Turning Dataframe into Graph with for loop with NetworkX

Viewed 45

I have this dataframe:

MATNR   PSTAT   MTART   MATKL   MEINS   BSTME   ZEINR   WRKST   NORMT   EKWSL   BRGEW
0       KDEA    ZHLB    99999   EA              Z005    0.089   0.089   0       FT3
1       KDVC    ZPLN    99000   EA                      3.14    3.14    0.015   FT3
2       KDVC    ZPLN    99000   EA                      3.14    3.14    0       FT3
3       KDVC    ZPLN    99000   EA                      3.14    3.14    0.02    FT3

and I am trying to turn it into a graph with networkX. This is the code I have thus far:

G = nx.Graph()

num_row = len(attr_df)
keys = len(attr_df.columns)
attrs = {}

for i in range(num_row):
    G.add_node(attr_df['MATNR'][i], 'PSTAT'='KDEA', 'MTART' = 99999, ...)

The problem is each row has different attributes, and also if the dataset was to get more rows and columns the process of adding attributes and values would be tedious.

How can I iterate through each column to add the attributes and their value?

1 Answers

You can create nodes in a graph in the following was without a for loop:

import pandas as pd

import networkx as nx

data = {
    "MATNR": {0: 0, 1: 1, 2: 2, 3: 3},
    "PSTAT": {0: "KDEA", 1: "KDVC", 2: "KDVC", 3: "KDVC"},
    "MTART": {0: "ZHLB", 1: "ZPLN", 2: "ZPLN", 3: "ZPLN"},
    "MATKL": {0: 99999, 1: 99000, 2: 99000, 3: 99000},
    "MEINS": {0: "EA", 1: "EA", 2: "EA", 3: "EA"},
    "BSTME": {0: "Z005", 1: "3.14", 2: "3.14", 3: "3.14"},
    "ZEINR": {0: 0.089, 1: 3.14, 2: 3.14, 3: 3.14},
    "WRKST": {0: 0.089, 1: 0.015, 2: 0.0, 3: 0.02},
    "NORMT": {0: "0", 1: "FT3", 2: "FT3", 3: "FT3"},
    "EKWSL": {0: "FT3", 1: None, 2: None, 3: None},
    "BRGEW": {0: None, 1: None, 2: None, 3: None},
}

df = pd.DataFrame.from_dict(data)

G = nx.Graph()

# get list of node names
node_names = df["MATNR"].copy().to_list()

# get dict of node attributes without name
attributes_dict = df.drop("MATNR", axis=1).to_dict("records")

# create list of tuples [(node_name, attributes as dict)] to pass to graph
nodes_tuple = list(zip(node_names, attributes_dict))

# add nodes to graph
G.add_nodes_from(nodes_tuple)

Or if you want/have to do it in a for loop:

G = nx.Graph()

for index, row in df.iterrows():

    #create dict from row
    row_dict = row.to_dict()
    
    #adjust dict of specific nodes etc.

    #pop name and unpack dict to pass to graph
    G.add_node(row_dict.pop('MATNR'), **row_dict)
Related