Iterating through a GeoDataFrame

1,375 views
Skip to first unread message

Dmitriy Tarasov

unread,
Aug 20, 2021, 12:12:38 PM8/20/21
to geopandas
I am trying to iterate through a GeoDataFrame called incidents (that was created by reading the contents of a point shapefile using the GeoPandas read_file function; for every point in the old shapefile, the nearest node on a network needs to be found). The code is as follows:

import omsnx as ox
...
for incident in incidents:
    node_near_incidentox.distance.nearest_nodes(graph_proj, incident.geometry.x, incident.geometry.y, return_dist=False)
    incident_nodes.append(node_near_incident) # each node to get appended into another GeoDataFrame

This (specifically, the line that begins with "node_near_incident...") throws the following error:
AttributeError: 'str' object has no attribute 'geometry'

Why does each line (correct me if the terminology is wrong) in a GeoDataFrame treated as a string object, and what is the correct syntax for iterating through a GeoDataFrame?

Martin Fleischmann

unread,
Aug 21, 2021, 5:10:27 AM8/21/21
to geop...@googlegroups.com
Iterating over geopandas.GeoDataFrame has exactly the same behaviour as iterating over pandas.DataFrame. I’d recommend checking their guide https://pandas.pydata.org/docs/user_guide/basics.html#iteration

Yours `for incident in incidents` gives you column names, not rows.You will need itertuples or iterrows. But in this specific case, it will be faster to loop over xy series.

```
x_coords = incidents.geometry.x
y_coords = incidents.geometry.y

for x, y in zip(x_coords, y_coords):
    node_near_incident = ox.distance.nearest_nodes(graph_proj, x, y, return_dist=False)
    incident_nodes.append(node_near_incident)
```

Note that this code is not tested :).

Martin

--
You received this message because you are subscribed to the Google Groups "geopandas" group.
To unsubscribe from this group and stop receiving emails from it, send an email to geopandas+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/geopandas/4b738afd-5610-4761-b650-54da3cb775c9n%40googlegroups.com.

Dmitriy Tarasov

unread,
Aug 30, 2021, 10:15:07 PM8/30/21
to geopandas
Thanks! For my purposes, the following syntax seems to work:
 for indexrow in GeoDataFrameName.iterrows():
  <do something>
Reply all
Reply to author
Forward
0 new messages