[GIS] Returning lat and long of centroid point with GeoPandas

coordinatesgeopandaspythonshapelyxy

I would like to return the lat, lon or x, y from the point object in the following series as I plan to link them with an API I built that links OSM and NetworkX. The centroids will be added as new nodes for network analysis.

gp.GeoSeries(zones.centroid).x, and gp.GeoSeries(zones.centroid).y as outlined in docs raise the following error:

AttributeError: 'GeoSeries' object has no attribute 'x'

Modifying things a bit and printing list(gp.GeoSeries(zones.centroid)) return thousands of shapely points of the following format:

[... <shapely.geometry.point.Point object at 0x0000000024035940>,
<shapely.geometry.point.Point object at 0x0000000024035978>, 
<shapely.geometry.point.Point object at 0x00000000240359B0>, 
<shapely.geometry.point.Point object at 0x00000000240359E8>, 
<shapely.geometry.point.Point object at 0x0000000024035A20>, 
<shapely.geometry.point.Point object at 0x0000000024035A58>, 
<shapely.geometry.point.Point object at 0x0000000024035A90>, 
<shapely.geometry.point.Point object at 0x0000000024035AC8>]

The code I'm using is the following:

import geopandas as gp

zones = gp.GeoDataFrame.from_file(shp_file)

for index, row in zones.iterrows():
    print index, gp.GeoSeries(zones.centroid)

# result:
# 9700022.00    POINT (-122.8196050489696 54.00617624128658)
# 9700023.00    POINT (-122.7474362519174 53.99998921974029)
# 9700100.00    POINT (-121.4904983300892 53.98447191612864)
# 9700101.00    POINT (-122.5513619751679 53.73999791511078)
# 9700102.00    POINT (-123.0624037191615 53.62317549646422)
# 9700103.00    POINT (-123.0848175548173 54.05921695782788)

How can I return the x, y from the GeoPandas POINT object?

Best Answer

Ran into this problem myself. If you want the x and y as separate GeoDataFrame columns, then this works nicely:

gdf["x"] = gdf.centroid.map(lambda p: p.x)
gdf["y"] = gdf.centroid.map(lambda p: p.y)

Starting with GeoPandas 0.3.0, you can use the provided x and y properties instead:

gdf["x"] = gdf.centroid.x
gdf["y"] = gdf.centroid.y