2

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'
1

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

0

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']

1 Comment

The asker left this comment on an answer I have since deleted when I suggested they try the same thing: "Gives me: KeyError: 0"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.