# Finding the centroid of a merged polygon using shapely function

I have a polygon shapefile and I want to find the centroid of the polygon, and output the centroid as a new shapefile before I geocode. How I should do this with Python functions shapely and Fiona and not ArcPy or ArcMap?

``````with fiona.open(DESTINATION_FILE) as input:
input.schema['geometry'] = "Point"
with fiona.open('.cache\centroid.shp', 'w', 'ESRI Shapefile', input.schema.copy(), input.crs) as output:
for elem in input:
if elem['id'] == '0':
geom = shape(elem['geometry'])
elem['geometry'] = mapping(geom.centroid)
output.write(elem)
``````

With this code I don't get the x, y coordinate of the centroid, so what should I do to get that, because after getting the x,y coord I will still geocode it.

• What have you tried? It's not only easier to answer questions with a coding framework, it's also policy to close coding questions without code. Please Edit your question to show what you've attempted and report the problem you've encountered. – Vince Mar 29 '20 at 19:12
• i have placed the code i used – rachel Mar 29 '20 at 20:00

It sounds like what you want is X,Y attributes in the file for the centroid, right? In Shapely, the `centroid` property of a geometry returns a `Point` object. You can get X and Y using the `x` and `y` attributes on that point, e.g.

``````from shapely.geometry import Point

point = Point(23, 42)
print(point.x)
print(point.y)
``````

You'll also want to alter your output shapefile's `schema` to include fields for the `x` and `y`, and add them to the feature you write to the shapefile:

``````with fiona.open('output.shp', schema={'properties':{'x': 'float', 'y': 'float'}, 'geometry': 'Point'}, crs='epsg:4326', driver='Esri Shapefile') as sink:
feature = {'type': 'Feature', 'properties': {'x': point.x, 'y': point.y}, 'geometry': mapping(point)
sink.write(feature)
``````