Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: 'NodeView' object does not support item assignment - NetworkX

I'm working through this tutorial: https://www.datacamp.com/community/tutorials/networkx-python-graph-tutorial

import itertools
import copy
import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt    
nodelist = pd.read_csv('https://gist.githubusercontent.com/brooksandrew/f989e10af17fb4c85b11409fea47895b/raw/a3a8da0fa5b094f1ca9d82e1642b384889ae16e8/nodelist_sleeping_giant.csv')

g = nx.Graph()

for i, nlrow in nodelist.iterrows():
    g.node[nlrow['id']] = nlrow[1:].to_dict()

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-80-35b1a259a02d> in <module>()
      1 for i, nlrow in nodelist.iterrows():
----> 2     g.node[nlrow['id']] = nlrow[1:].to_dict()

TypeError: 'NodeView' object does not support item assignment

The result from running this should look like:

[('rs_end_south', {'X': 1865, 'Y': 1598}),
 ('w_gy2', {'X': 2000, 'Y': 954}),
 ('rd_end_south_dupe', {'X': 273, 'Y': 1869}),
 ('w_gy1', {'X': 1184, 'Y': 1445}),
 ('g_rt', {'X': 908, 'Y': 1378}),
 ('v_rd', {'X': 258, 'Y': 1684}),
 ('g_rs', {'X': 1676, 'Y': 775}),
 ('rc_end_north', {'X': 867, 'Y': 618}),
 ('v_end_east', {'X': 2131, 'Y': 921}),
 ('rh_end_south', {'X': 721, 'Y': 1925})]

But I can't get python to output the id followed by the dict.

like image 605
conv3d Avatar asked Oct 31 '17 22:10

conv3d


1 Answers

Instead of:

g.node[nlrow['id']] = nlrow[1:].to_dict()

use:

g.nodes[nlrow['id']].update(nlrow[1:].to_dict())

This works because g.nodes[x] is nothing else than a dict. Nevertheless, I'm not sure why the documentation proposes the other way.

Note:

Joel made a good point in the comments, which I think is very important:

Note - you're using networkx version 2.0, right? It's very recent, and so I suspect that this is an incompatibility from the person writing it using version 1.11. I think networkx provides ways to do what these commands are trying to do without directly editing the underlying data structure of the graph.

So my solution basically works by having knowledge about the underlying data structure and not using the public api, which is not good programming style.

Since Version 2.4, G.node is deprecated in favor of G.nodes (Thank you, WiccanKarnak).

like image 170
Murmel Avatar answered Oct 20 '22 17:10

Murmel