'Graph' object has no attribute 'node'

Question:

I have this code which runs perfectly fine.

G = nx.Graph()

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

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

and if I was to call

G.nodes()

I would get a long list of all the nodes.

But when I call

G.node[0]

to look at an individual node and its properties, I get:

AttributeError: 'Graph' object has no attribute 'node'
Asked By: Owen

||

Answers:

G.nodes() is a method that returns a NodeView object. There is no value being created called G.node that can be iterated over.

You can cast NodeView to a list like this list(NodeViewObj), and therefore access the first element like so:

list(G.nodes())[0]

The documentation details this

Answered By: Libra

While @Libra’s answer is correct, it’s also possible to access a specific node via G.nodes[node_name] syntax. For example, the following should work if node 0 is a node in G:

G.nodes[0]

This provides a convenient way to access nodes, especially if they have a non-numeric name, when relying on their position in list(G.nodes()) is not so reliable, while you can still call out them using their string name, e.g. G.nodes['B']

Answered By: SultanOrazbayev
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.