3

I just started working with shapefiles. I need to take polygon # 93 (Sea of ​​Japan) in a large shapefile and build a sea map in bokeh Python. How do I refer to a specific polygon in a shapefile?

import shapefile

shape = shapefile.Reader("С:/World_Seas_IHO_v3.shp") # There are 101 polygons in total, the polygon I need is 93
#first feature of the shapefile
feature = shape.shapeRecords()[0]
first = feature.shape.__geo_interface__  
print(first) # 
0

2 Answers 2

7

The result is a dictionary (GeoJSON format, see Python Geo_interface applications for example)

import shapefile
r = shapefile.Reader("polys.shp")
rec = r.shapeRecords()[7]
geom = rec.shape.__geo_interface__
print(geom) # GeoJSON format)
{'type': 'Polygon', 'coordinates': [[(245402.24387797402, 1000578.2015550972), (245597.81746161517, 1000599.6342765922), (245640.682904605, 1000453.623861408), (245395.54615250687, 1000450.9447712211), (245402.24387797402, 1000578.2015550972)]]}
# therefore
coords = geom['coordinates'] # or directly rec.shape.__geo_interface__['coordinates']
print(coords)
[[(245402.24387797402, 1000578.2015550972), (245597.81746161517, 1000599.6342765922), (245640.682904605, 1000453.623861408), (245395.54615250687, 1000450.9447712211), (245402.24387797402, 1000578.2015550972)]]

New

for i in coords[0]:
    print(i)

(245402.24387797402, 1000578.2015550972)
(245597.81746161517, 1000599.6342765922)
(245640.682904605, 1000453.623861408)
(245395.54615250687, 1000450.9447712211)
(245402.24387797402, 1000578.2015550972)
0
5

You can also get your points simply via points:

The points attribute contains a list of tuples containing an (x,y) coordinate for each point in the shape.

import shapefile

shape = shapefile.Reader("C:/TempData/test/grids.shp")

feature = shape.shapeRecords()[0]

points = feature.shape.points
print(points)

That results in

[(413795.5781, 5655831.7174), (413895.5781, 5655831.7174), (413895.5781, 5655731.7174), (413795.5781, 5655731.7174), (413795.5781, 5655831.7174)] 

Also with this method one can refer to a specific point of a feature:

point2 = feature.shape.points[2] # vertex #2
print(point2)

will give you

(413895.5781, 5655731.7174)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.