Geographic Information Systems Asked by Ger on January 26, 2021
I read a shapefile with GeoPandas and I get a nice table with a column "geometry"
. This column contains shapely.geometry.polygon.Polygon
or shapely.geometry.multipolygon.MultiPolygon
object.
import geopandas as gpd
gdf = gpd.GeoDataFrame.from_file("ashapefile.shp")
Now I would like to use this geoDataFrame to make such as a chloropeth plot or something else. Thus I would like to get the (x, y) coordinates, (latitude, longitude) of these polygons.
For example if I do :
for boundary in gdf.boundary:
print(boundary.xy)
Thus boundary
are shapely.geometry.linestring.LineString
or MultiLineString
. boundary.xy
are what I am looking for. But for MultilineString I have to do a loop on all the line.
Is there the way to do that ? Or is there a more simple or straightforward way ?
EDIT :
Issue with unary_union
:
A polygons shapefile
import geopandas as gpd
gdf = gpd.read_file("polys.shp")
gdf.head(2)
Number of polygons
gdf.groupby('POLY_NUM_B').count()
Pb Zn geometry
POLY_NUM_B
24 1 1 1
25 1 1 1
26 1 1 1
27 1 1 1
28 1 1 1
Extraction of the the nodes of the polygons exterior coordinates (Shapely: polygon)
from shapely.geometry import Point
for index, row in gdf.iterrows():
for pt in list(row['geometry'].exterior.coords):
print Point(pt)
POINT (-716632.5126561673 -954202.6388434628)
POINT (-716599.344199169 -954224.8253932064)
POINT (-716538.7964301996 -954240.9772354551)
POINT (-716529.3520701742 -954273.9782994529)
POINT (-716550.9210327187 -954269.8358586552)
POINT (-716600.4004366234 -954260.3328329064)
POINT (-716627.870139441 -954255.056896301)
POINT (-716639.1558135629 -954227.2907514013)
....
With MultiPolygons, you need to adapt the script or use Shapely unary_union
(conversion of a MultiPolygon to a Polygon) before as in Geopandas [Shapely] spatial difference: TopologyException: no outgoing dirEdge found
Creation of a new nodes (Points) GeoDataFrame with the columns of gdf
col = gdf.columns.tolist()[0:4]
print col
[u'POLY_NUM_B', u'Pb', u'Zn', 'geometry']
# New GeoDataFrame
nodes = gpd.GeoDataFrame(columns=col)
# extraction of nodes and attribute values nouveau GeoDataFrame
for index, row in gdf.iterrows():
for pt in list(row['geometry'].exterior.coords):
nodes = nodes.append({'POLY_NUM_B': int(row['POLY_NUM_B']), 'Pb':row['Pb'],'Zn':row['Zn'], 'geometry':Point(pt) },ignore_index=True)
nodes.head(5)
Number of nodes of polygons
nodes.groupby('POLY_NUM_B').count()
Pb Zn geometry
POLY_NUM_B
24.0 9 9 9
25.0 10 10 10
26.0 7 7 7
27.0 6 6 6
28.0 6 6 6
Answered by gene on January 26, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP