python - 类型错误 : 'NodeView' object does not support item assignment - NetworkX

标签 python networkx

我正在学习本教程: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

运行它的结果应该如下所示:
[('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})]

但我无法让 python 输出 id其次是字典。

最佳答案

代替:

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

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

这是因为 g.nodes[x]只不过是一个字典。不过,我不确定为什么文档会提出另一种方式。

注:

乔尔提出了一个很好的观点in the comments ,我认为这很重要:

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.



所以我的解决方案基本上是通过了解底层数据结构而不使用公共(public) api 来工作的,这不是好的编程风格。

Since Version 2.4 , G.node已弃用,取而代之的是 G.nodes (谢谢你,WiccanKarnak)。

关于python - 类型错误 : 'NodeView' object does not support item assignment - NetworkX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47045155/

相关文章:

Python:两个网络之间的jaccard相似性?

python - 了解 Scrapy 中的回调

python - Networkx 图搜索 : dfs_successors vs. dfs_predecessors

matplotlib - 为什么 NetworkX 在执行时会自动旋转图形

python - 使用python从带有滚动的网页中抓取数据

python - NetworkX 有向图,无权值和自弧

python - NetworkX/Pandas - 无法将节点的度数输出到 .txt 文件中(错误消息)

python - 属性错误 : 'module' object has no attribute 'OP_NO_TLSv1_1

python - 我在将 unicode 转换为字符串时遇到困难

python - 使用 MagicMock 在 Python 中模拟嵌套导入