Search code examples
pythonnetworkx

nx.set_node_attributes not adding the two attributes from either datafram or dict


I need to create a graph object, with two attributes for each node.

When I create this and add node attributes, I cannot correctly retrieve the values when I call specific nodes.

The code I am using to create the graph object is as follows:

nodes = pd.DataFrame(data=N)

E = {'from': ['1','2', '1','5','D','D','D','03','1'],
     'to': ['2','1','5','D','1','1','Z','Z','2'],
     'counts':[22,20,13,15,19,21,20,27,15]}
edges = pd.DataFrame(data=E)

nodes = nodes.set_index('node').T.to_dict('index')


X = nx.from_pandas_edgelist(edges, source = 'from', target = 'to', edge_attr = 'counts')
nx.set_node_attributes(X, nodes, 'mode'

Using nx.get_node_attributes I am unable to retrieve the attributes applied.

nx.get_node_attributes(X, '1') returns {}

I have also tried creating a graph with nx.graph() and subsequently adding the nodes but it ultimately returns the same result

How can I correctly add node attributes to my graph object?


Solution

  • To answer my question, for those in the future. The following code added the attributes required:

    G = nx.from_pandas_edgelist(df, 'from', 'to', True, nx.DiGraph())
    nx.set_node_attributes(G, all_stations.set_index('node').to_dict('index'))
    G.nodes["Z"]
    

    A slight change but successful result