Skip to main content
42 votes
Accepted

Welding individual line segments into one LineString using Shapely

You can use shapely's ops.linemerge to accomplish this: from shapely import geometry, ops # create three lines line_a = geometry.LineString([[0,0], [1,1]]) line_b = geometry.LineString([[1,1], [1,0]]...
songololo's user avatar
  • 1,724
33 votes

Returning lat and long of centroid point with GeoPandas

Ran into this problem myself. If you want the x and y as separate GeoDataFrame columns, then this works nicely: gdf["x"] = gdf.centroid.map(lambda p: p.x) gdf["y"] = gdf.centroid.map(lambda p: p.y) ...
Martin Valgur's user avatar
32 votes

Transforming Shapely Polygon and MultiPolygon objects

If you're using pyproj2, it's much easier to use a Transformer. Here's an example: import pyproj from shapely.ops import transform project = pyproj.Transformer.from_proj( pyproj.Proj(init='epsg:...
Nick ODell's user avatar
28 votes
Accepted

Removing small holes from the polygon

You can use the following example script. The script removes all holes from a polygon whose area is smaller than eps. from shapely import wkt from shapely.geometry import Polygon # sample polygon ...
Kadir Şahbaz's user avatar
27 votes
Accepted

Returning percentage of area of polygon intersecting another polygon using shapely

Next code: import fiona from shapely.geometry import shape path1 = '/home/zeito/pyqgis_data/polygon1.shp' path2 = '/home/zeito/pyqgis_data/polygon8.shp' polygon1 = fiona.open(path1) polygon8 = ...
xunilk's user avatar
  • 30.2k
26 votes

Make shapefile from raster-bounds in Python

With shapely box and GeoPandas import rasterio as rio ra = rio.open("raster.tif") bounds = ra.bounds Convert bounds to shapely geometry from shapely.geometry import box geom = box(*bounds) print(...
gene's user avatar
  • 55.4k
24 votes
Accepted

Converting Polygon to MultiPolygon with Shapely?

You can wrap the polygon in a list and pass that as an argument to the MultiPolygon constructor. Demo: from shapely.geometry.multipolygon import MultiPolygon from shapely import wkt p = wkt.loads(u'...
jpmc26's user avatar
  • 1,719
24 votes
Accepted

Looking for GeoPandas QGIS equivalent of ArcGIS "Select by location" tool

If poly is a GeoDataFrame with a single geometry, extract this: polygon = poly.geometry[0] Then, you can use the within method to check which points are within the polygon: points.within(polygon) ...
joris's user avatar
  • 3,943
24 votes
Accepted

Shapely coordinate sequence to GeoDataFrame

Make a shapely polygon geometry from coordinate pairs. Pass the polygon to GeoDataFrame constructor as a list. import geopandas as gpd from shapely.geometry import Polygon coords = [(151....
Kadir Şahbaz's user avatar
21 votes

Getting polygon breadth in Shapely

# create example polygon poly = Polygon([(0, 0), (4, 0), (5, 2), (7, 5), (3, 2), (1, 3)]) # get minimum bounding box around polygon box = poly.minimum_rotated_rectangle # get coordinates of polygon ...
Vaiaro's user avatar
  • 548
20 votes
Accepted

Calculate distance from a Point within a Polygon to its edge

Compare the point to the polygon's exterior ring: poly.exterior.distance(point)
sgillies's user avatar
  • 9,066
20 votes
Accepted

Plotting Shapely Multipolygon using Matplotlib

Shapely Polygon object has attribute exterior. Shapely MultiPolygon object has Polygon object sequence. You should iterate over those polygons. You can do that using attribute geoms of MultiPolygon. ...
Kadir Şahbaz's user avatar
19 votes
Accepted

Intersecting two shape problem using geopandas

1) The problem is that the intersection of two polygons is not always a polygon import geopandas as gp poly1 = gp.read_file("poly_origin.shp") poly2 = gp.read_file("poly_test.shp") data = [] for ...
gene's user avatar
  • 55.4k
19 votes
Accepted

Auto-select suitable UTM Zone based on Grid Intersection

There's the utm package, a bidirectional UTM-WGS84 converter for python. It's able to convert a (latitude, longitude) tuple into an UTM coordinate: import utm utm.from_latlon(51.2, 7.5) >>> (...
Antonio Falciano's user avatar
18 votes

Rounding all coordinates in shapely

There are a few instances where @gene's answer does not work. For example, the using the overprecise value -73.92391000000001 geojson = {'type': 'Polygon', 'coordinates': [[[-73.92391, 41.31064], [-...
koshmaster's user avatar
17 votes
Accepted

Drawing ellipse with shapely

Answer First, define a circle of radius 1. Then define an ellipse along x and y axis. Rotate the ellipse. Finally, actually draw the ellipse. Code from matplotlib import pyplot from shapely.geometry....
swiss_knight's user avatar
  • 10.9k
16 votes

Auto-select suitable UTM Zone based on Grid Intersection

Alright, the answer from Antonio above is definitely right and pointed me in the correct direction. Here is the complete code: # convert_wgs_to_utm function, see https://stackoverflow.com/a/40140326/...
Alex's user avatar
  • 714
16 votes
Accepted

Shapely polygon union results in strange artifacts of tiny, non-overlapping areas

This is typically a result of the the borders not fitting perfectly one next to another (and this is very easy to get with floating point coordinates). As an example, I use the world dataset ...
joris's user avatar
  • 3,943
15 votes
Accepted

Geopandas Line Polygon Intersection

When comparing geodataframes with geometry operations in Geopandas, the geometries are first matched by index. In the case where there is no matching index (because you only have a single polygon for ...
om_henners's user avatar
  • 15.7k
15 votes

Snap points shapefile to line shapefile using shapely

The methodology is called linear referencing and a solution was given by Mike T in Coordinate of the closest point on a line with Shapely. There is also a recipe in the Python Geospatial Analysis ...
gene's user avatar
  • 55.4k
15 votes
Accepted

Flipping coordinates with Shapely

You can use a simple transformation function with shapely.ops' transform function. For example: def flip(x, y): """Flips the x and y coordinate values""" return y,...
inc42's user avatar
  • 830
14 votes

What is unit of Shapely length attribute?

You can now use shapely w/ pyproj to get geodesic length in meters: From: https://pyproj4.github.io/pyproj/stable/api/geod.html#pyproj.Geod.geometry_length from pyproj import Geod from shapely....
Josh Werts's user avatar
14 votes
Accepted

Splitting line by nearest points using GeoPandas

First make sure you union your GeoDataFrames into a MultiLineString and MultiPoint line = gdf_line.geometry.unary_union coords = gdf_point.geometry.unary_union Using shapely.ops.snap and shapely.ops....
Mattijn's user avatar
  • 1,006
14 votes
Accepted

Shapely - convert polygons to lines?

bugmenot123 is ok but I find easier use the boundary of the polygons. If you have a multipolygon or a polygon with holes the boundary returns a multilinestrig, if you have a polygon without holes the ...
César Argul García's user avatar
14 votes
Accepted

How to extract biggest Polygon from MultiPolygon in GeoPandas?

Here's what I would do: max(multipolygon, key=lambda a: a.area) The built-in max function used this way will return the item from the list where lambda a: a.area is maximized.
Paul H's user avatar
  • 915
14 votes
Accepted

Filtering by geometry type in GeoPandas

There are many solutions (see How to filter a geodataframe by geometry type? for example) With .loc as you but with geometry.type or geom_type gdf0 = gdf.loc[gdf.geometry.geometry.type=='MultiPolygon']...
gene's user avatar
  • 55.4k
14 votes

Is the LineString straight?

Maths should always work. You can basically test for the collinearity between the first vector of the line (i.e. composed by the two first points of the line) and all other vectors of the line (i.e. ...
swiss_knight's user avatar
  • 10.9k
14 votes

Is the LineString straight?

A really simple way is to evaluate the sinuosity for each linestring, using something like this for shapely: def sinuosity(geom): assert geom.geom_type == "LineString", geom.geom_type ...
Mike T's user avatar
  • 42.4k
13 votes
Accepted

Filter a GeoPandas dataframe for points within a specific country

Did you see More Efficient Spatial join in Python without QGIS, ArcGIS, PostGIS, etc and other answers on GIS SE ? Simply import geopandas as gpd world = gpd.read_file(gpd.datasets.get_path('...
gene's user avatar
  • 55.4k
13 votes

Interchange y, x to x, y with geopandas (python) or QGIS

shapely.ops.transform module allows passing a function to operate on coordinates. Therefore if you want to swap x, y coordinates in a GeoDataFrame you can use : import shapely gdf.geometry.map(lambda ...
MCMZL's user avatar
  • 241

Only top scored, non community-wiki answers of a minimum length are eligible