I have a geojson file of county/unitary authorities (UTLAs) in the UK that I have read in using geopandas. I am trying to get a shapely polygon of each UTLA, but I am running into problems with UTLAs that contain other UTLAs (ie interior polygons), for example Derbyshire.
I am trying to extract the coordinates for the interior polygon:
import geopandas as gpd
utla_polygons = gpd.read_file('https://opendata.arcgis.com/datasets/244b257482da4778995cf11ff99e9997_0.geojson')
derbs = utla_polygons[utla_polygons['CTYUA21NM']=='Derbyshire']
derbs_int = derbs.explode().geometry.interiors
derbs_int
derbs_int is how I would expect it to be, based on the geopandas documentation :
130 0 [LINEARRING (-1.484521649999976 52.96638748100...
dtype: object
However, when I try to extract the coordinates from derbs_int, I get the following error:
derbs_int.coords
AttributeError: 'Series' object has no attribute 'coords'
How can I extract these coordinates so I can use them to create a shapely polygon?
One way to convert a multipoygon to a single polygon is by accessing the JSON and get the first element in the list.
import json
from shapely.geometry import shape
import requests
url = 'https://opendata.arcgis.com/datasets/244b257482da4778995cf11ff99e9997_0.geojson'
r = requests.get(url)
data = json.loads(r.text)
for f in data['features']:
if f['properties']['CTYUA21NM'] == 'Derbyshire':
geom = f['geometry']
# convert MultiPolygon > Polygon
geom = shape({
'type': 'Polygon',
'coordinates': geom['coordinates'][0]
})
print(type(geom))
break
Output:
<class 'shapely.geometry.polygon.Polygon'>
Need to be systematic. Multi-polygons include polygons, polygons include interiors, interiors have co-ordinates
import geopandas as gpd
import requests
res = requests.get(
"https://opendata.arcgis.com/datasets/244b257482da4778995cf11ff99e9997_0.geojson"
)
gdf = gpd.GeoDataFrame.from_features(res.json()).set_crs("epsg:4326")
gdfd = gdf.loc[gdf["CTYUA21NM"].str.contains("Derbyshire")].copy()
gdfd["geometry"].apply(
lambda g: [g3.coords for g2 in g.geoms for g3 in g2.interiors]
).explode().explode()
130 (-1.484521649999976, 52.96638748100003)
130 (-1.484809956999925, 52.96630955400008)
130 (-1.484938351999972, 52.96627955300005)
130 (-1.485184568999955, 52.96623118800005)
130 (-1.48530681099993, 52.96621284400004)
...
130 (-1.483622200999946, 52.96727346400007)
130 (-1.483387032999929, 52.96689850300004)
130 (-1.483327163999945, 52.966792199000054)
130 (-1.483532068999978, 52.966718497000045)
130 (-1.484521649999976, 52.96638748100003)
Name: geometry, Length: 1587, dtype: object
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.