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