DPM
DPM

Reputation: 935

Adding an attribute to a node in osmnx

I am trying to add an attribute to my nodes in the osmnx network I have in order to use the ox.plot.get_node_colors_by_attr() later on. However I am unable to properly add the attribute.

Here is the code:

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

This gives me:

enter image description here

Which is incorrect since the attr column is just all 1.

Here are a few values of my list:

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

Upvotes: 0

Views: 1588

Answers (1)

gboeing
gboeing

Reputation: 6412

Without a reproducible example, it's difficult to guess what r_total contains or how you're using it. Here's how you could get the value of r_total, by looking up a value at a position where the position is defined by the node ID (i.e., the label of the nodes GeoDataFrame):

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()

Upvotes: 2

Related Questions