Is there a generic way to flip/invert/reverse the order of the coordinates of a shapely
geometry?
Here are a couple of examples of what I mean.
Example 1
Input: LINESTRING (0 0, 1 1, 3 1, -3 3)
Output: LINESTRING (-3 3, 3 1, 1 1, 0 0)
Example 2
Input: MULTILINESTRING ((120 105, 140 98),(160 103, 140 98),(100 100, 120 105))
Output: MULTILINESTRING ((120 105, 100 100), (140 98, 160 103), (140 98, 120 105))
My implementation (small reproducible example)
I was able to put together a small implementation for LineStrings and MultiLineStrings. Note that it is not efficient at all and it doesn't account for the vast amount of shape types (polygons, multipolygons, etc).
import shapely
# Shape inverter
def invert_coords(input_geom):
if input_geom.type.lower() == 'linestring':
coords = [tuple(coord) for coord in list(input_geom.coords)][::-1]
out_geom = shapely.geometry.LineString(coords)
elif input_geom.type.lower() == 'multilinestring':
coords = [list(this_geom.coords)[::-1] for this_geom in input_geom.geoms][::-1]
out_geom = shapely.geometry.MultiLineString(coords)
return out_geom
# Write the WKTs
ls_wkt = 'LINESTRING (0 0, 1 1, 3 1, -3 3)'
mls_wkt = 'MULTILINESTRING ((120 105, 140 98),(160 103, 140 98),(100 100, 120 105))'
# Generate the shapely geometries
ls = shapely.wkt.loads(ls_wkt)
mls = shapely.wkt.loads(mls_wkt)
# Inverting shapes
ls_inv = invert_coords(ls)
mls_inv = invert_coords(mls)
print(ls_inv.wkt)
# LINESTRING (-3 3, 3 1, 1 1, 0 0)
print(mls_inv.wkt)
# MULTILINESTRING ((120 105, 100 100), (140 98, 160 103), (140 98, 120 105))
Back to the main question
Is there a generic yet straightforward way of inverting the order of the coordinates for any shapely
geometry?