在osmnx中向节点添加属性

时间:2020-07-07 20:45:58

标签: python networkx osmnx

我正尝试在osmnx网络中的节点上添加属性,以便以后使用ox.plot.get_node_colors_by_attr()。 但是,我无法正确添加属性。

代码如下:

city = 'Portugal, Lisbon'
G = ox.graph_from_place(city, network_type='drive', simplify=True)
G_nx = nx.relabel.convert_node_labels_to_integers(G)

nodes, edges = ox.graph_to_gdfs(G_nx, nodes=True, edges=True)

nodes['attr'] = 0
i = 0
for node in G_nx.nodes:
        
    nodes['attr'][node] = r_total[0][i]   ##r_total[0][i] contains the values I am adding

i +=1

这给了我

enter image description here

这是不正确的,因为attr列全为1。

以下是我的列表中的一些值:

r_total[0] = [1.1437781610893372,1.1581102825247183,1.352684838232266,1.0511223206671774,1.1369540060020151,
1.1639685722826303,1.3451475522422993,-1,1.0416972740013004,1.0240843300890685,1.411806610408149...]

1 个答案:

答案 0 :(得分:1)

没有可复制的示例,很难猜测r_total包含的内容或使用方式。通过在由节点ID(即r_total GeoDataFrame的标签)定义的位置上查找一个值来获取nodes的值的方法如下:

import networkx as nx
import numpy as np
import osmnx as ox
ox.config(use_cache=True, log_console=True)

city = 'Portugal, Lisbon'
G = ox.graph_from_place(city, network_type='drive', simplify=True)

G_nx = nx.relabel.convert_node_labels_to_integers(G)
nodes, edges = ox.graph_to_gdfs(G_nx, nodes=True, edges=True)

r_total = np.random.random(len(G_nx))
nodes['attr'] = nodes.index.map(lambda x: r_total[x])
nodes.head()