8

How do I modify an existing Polygon? For a start, I'd like to add a Point to its exterior.

poly = Polygon([(0, 0), (1, 1), (1, 0)])

I was looking for something like this:

poly.append_at(idx=3, Point(1, -1))

But I cannot find any even similar methods for doing this.

Georgy
  • 12,464
  • 7
  • 65
  • 73
racic
  • 1,235
  • 11
  • 20

1 Answers1

12

It doesn't make sense to add or remove points from a Polygon's exterior, because you'd want to recalculate poly.area, poly.length, etc. anyway. Instead, create a new Polygon instance from the old polygon's coordinates:

coords = poly.exterior.coords[:]
coords[1] = (2.0, 6.0) # coordinate to change

new_poly = Polygon(coords)

Note that this doesn't account for points in poly.interior.

Mike T
  • 41,085
  • 18
  • 152
  • 203
Lynn
  • 10,425
  • 43
  • 75
  • 1
    @MikeToews: Re your comment below (may be deleted now) - I understand "immutable", but the very next statement in the documentation says "Their parent features are mutable in that they can be assigned new coordinate sequences.". That's what I was trying to do, assign a new sequence. For all I knew, an assignment of a new coord sequence **might** have triggered a re-calculation of area, centroid, etc. So I think the docs are a little misleading on that point. – subnivean Jan 03 '13 at 02:21
  • @subnivean agreed, this blurb in the manual is not clear; see https://github.com/Toblerity/Shapely/issues/38 – Mike T Jan 03 '13 at 03:16