gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:28:08 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com