I have a shapefile that contains several thousand / and another shapefile that has a variable number of LineStrings.  In the example below the blue Polygons are those that intersect with the red LineString and the brown Polygons are those that do not.   I am using the Shapely  binary predicate to check whether each LineString intersects with any one of the Polygons:  import fiona from shapely.geometry import LineString, Polygon, MultiPolygon  # Open each layer poly_layer = fiona.open('polygon_layer.shp', 'r') line_layer = fiona.open('line_layer.shp', 'r')  # Create each Polygon/MultiPolygon the_polygons = [] for poly in poly_layer:     if poly['geometry']['type'] == 'Polygon':         the_polygons.append((poly['properties']['poly_id'],                              Polygon(poly['geometry']['coordinates'][0])))     elif poly['geometry']['type'] == 'MultiPolygon':         all_polygons = []         for poly_coords in poly['geometry']['coordinates']:             all_polygons.append(Polygon(poly_coords[0]))          the_polygons.append((poly['properties']['poly_id'],                               MultiPolygon(all_polygons)))     else:         print poly['geometry']['type']         raw_input()  # Create each LineString the_lines = [] for line in line_layer:     the_lines.append(LineString(line['geometry']['coordinates']))  # Check for Polygons/MultiPolygons that the LineString intersects with covered_polygons = {} for poly_id, poly in the_polygons:     for line in the_lines:         if poly.intersects(line):             covered_polygons[poly_id] = covered_polygons.get(poly_id, 0) + 1   The above code takes a long time to run, and being new to Fiona and Shapely I am not sure that this is the most efficient way to accomplish things.  So is there a better way to do what I want?  Edit: The key to speeding up the computations was to use a spatial index.  The linked question does not have what I believe is the fastest solution - using GeoPandas.
120582
What I'd like to try and do is intersect some point buffers with census tracts, maintain their ID's and the tracts attributes.  I found a sample from  but can't exactly substitute the cascaded union for an intersect. I'm also having trouble getting the intersection function to import from shapely.ops.   from shapely.geometry import Point, mapping, shape from fiona import collection #from shapely.ops import intersection import shapely.ops  bufSHP = 'data/h1_buf.shp' intSHP = 'data/h1_buf_int_ct.shp' ctSHP  = 'data/nyct2010.shp' with collection(bufSHP, "r") as input:     schema = input.schema.copy()     with collection(intSHP, "w", "ESRI Shapefile", schema) as output:         shapes = []         for f in input:             shapes.append(shape(f['geometry']))         merged = shapes.intersection(ctSHP)         output.write({             'properties': {                 'uid': point['properties']['uid']                 },             'geometry': mapping(merged)             })   I've also got the code and sample shapefiles up here     UPDATE:  So for some reason using Shapely, the larger buffers (1 km) I lose some of the features (census tracts) in the intersect.   Also, since the Shapely responder said the OGR command is good to use I started looking for into that. Anyway, I was able to test cd'ing to the directory and it works great. However, I've been trying to experiment with it so I can loop through the many sized buffers and dif. census years. However, why is it that I cannot get the following script to work. Can I not substitute paths for the folder 'data' in the ogr2ogr response below?   import os wp = '/Volumes/Echo/GIS/projects/naas/tasks/201411_geoprocessing/data/processing/' folder = wp+'test' theGDALcmd = 'ogr2ogr -sql "SELECT ST_Intersection(A.geometry, B.geometry) AS geometry, A.*, B.* FROM nyct2010 A, hr1000m B WHERE ST_Intersects(A.geometry, B.geometry)" -dialect SQLITE '+folder+' '+folder+' -nln hr1000m_int_ct10_ogr_pytest' os.system(theGDALcmd)   The error I get is   sh: ogr2ogr: command not found   However, when I go to the terminal, I have access to ogr2ogr.     UPDATE2:  Mike T include some code so I can run this ogr2ogr command in python.
104865
How can I access (read/write) m values of a line Shapefile using pyqgis?   I know how to do it with arcpy cursors ( ) but I don't know how to do it with pyqgis.   Is it possible with the QGIS python library?
87718
I have created a table join between two shapefiles which I've named 'OSMM' and 'Mastermap'. I want to copy and paste all features (polygons) without a match from the target layer ('Mastermap') into the parent shapefile ('OSMM'). I can't find any up-to-update code for QGIS 3.6. Here is my code so far: #1. loads the SHP files uri = 'C:/Users/xx/Downloads/OSMM.shp' vlayer = iface.addVectorLayer(uri,&quot;&quot;,&quot;ogr&quot;) uri = 'C:/Users/xx/Downloads/Mastermap.shp' vlayer = iface.addVectorLayer(uri,&quot;&quot;,&quot;ogr&quot;)  #2. Joins &quot;InvoiceNum&quot; from OSMM to Mastermap layerToJoin = QgsProject().instance().mapLayersByName('OSMM')[0] target = QgsProject().instance().mapLayersByName('Mastermap')[0] myJoin = QgsVectorLayerJoinInfo() myJoin.setJoinFieldName('InvoiceNum') myJoin.setTargetFieldName('InvoiceNum') myJoin.setJoinLayerId(layerToJoin.id()) myJoin.setUsingMemoryCache(True) myJoin.setJoinLayer(layerToJoin) myJoin.setJoinFieldNamesSubset(['InvoiceNum']) target.addJoin(myJoin)  #3. Selects NULL features from Mastermap params = { 'EXPRESSION' : '\&quot;OSMM_InvoiceNum\&quot; is NULL', 'INPUT' : 'C:/Users/xx/Downloads/Mastermap.shp', 'METHOD' : 0 } processing.run(&quot;qgis:selectbyexpression&quot;, params)  So how do I perform the PyQGIS version of Ctrl+C on 'Mastermap' and Ctrl+V into 'OSMM'? Presumably I will then need to use the following code: #5. Save the changes OSMM.commitChanges()
62326
I have a PostGIS table of polygons where some intersect with one another.  This is what I'm trying to do:   For a given polygon selected by id, give me all of the polygons that intersect.  Basically, select the_geom from the_table where ST_Intersects(the_geom, (select the_geom from the_table where source_id = '123')) From these polygons, I need to create a new polygons such that intersection becomes a new polygon.  So if polygon A intersects with polygon B, I will get 3 new polygons: A minus AB, AB, and B minus AB.   Any ideas?
24602
I have a polygon which is actually composed of many polygons but it results as unique geometry in the shapefile. It's easier to explain with a picture. The yellow parts are in my shapefile a single polygon. I want to make each part be a different polygon with different attributes.    I tried with "Multiparts to single part" but the result is another layer with only those polygons. I need instead a unique layer.
122454
I'm attempting to do a spatial join much like the example here: . However, that approach seems really inefficient / slow. Even running this with a modest 250 points takes almost 2 minutes and it fails entirely on shapefiles with > 1,000 points. Is there a better approach? I'd like to do this entirely in Python without using ArcGIS, QGIS, etc.  I'd also be interested to know if it's possible to SUM attributes (i.e. population) of all the points that fall within a polygon and join that quantity to the polygon shapefile.       Here is the code I'm trying to convert. I get an error on line 9:  poly['properties']['score'] += point['properties']['score']   which says:     TypeError: unsupported operand type(s) for +=: 'NoneType' and 'float'.    If I replace the "+=" with "=" it runs fine but that doesn't sum the fields. I've also tried making these as integers but that fails as well.  with fiona.open(poly_shp, 'r') as n:    with fiona.open(point_shp,'r') as s:     outSchema = {'geometry': 'Polygon','properties':{'region':'str','score':'float'}}     with fiona.open (out_shp, 'w', 'ESRI Shapefile', outSchema, crs) as output:         for point in s:             for poly in n:                 if shape(point['geometry']).within(shape(poly['geometry'])):                       poly['properties']['score']) += point['properties']['score'])                     output.write({                         'properties':{                             'region':poly['properties']['NAME'],                             'score':poly['properties']['score']},                         'geometry':poly['geometry']})
28459
I have a line layer and a polygon layer. Both files have the same SRS. I want in a new shape file only the lines covered by the polygons.   I tried in QGIS the Vector -&gt; Geoprocessing -&gt; Clip tool but I only get an empty shapefile.  How do I do this with QGIS?
93928
I have a shapefile with a single Polygon feature. This feature has a "ring not closed" geometry error (seen here in QGIS):   I tried using buffering and the GRASS v.clean command as suggested in other answers, but no luck. I also can't find the gap by inspecting the feature visually (it looks perfect).  I need a valid geometry here. Ideally, I'd like to have a Python/command line solution. Any way of doing this manually in QGIS/ArcGIS would also be great.  UPDATE: this shapefile can be downloaded .
74909
Following , can I have a mixture of two kinds of geometry in a shapefile of type point. Just like I have about shapefiles of type polygon or I should always create a shapefile of type multipoint in order to support multipoints in my layer?    My problem is as you see at , I can't use ogrinfo in order to understand that the geometry type of a multipoint shapefile will be known as wkbMultipoint or wkbPointwhen I use this line of code:    OGRwkbGeometryType GeometryType = poLayer -&gt;GetGeomType();     for a layer of type multipoint before programming.     Will OGR know a layer of type multipoint as wkbpoint or wkbmultipoint?   When we create a shapefile in ArcCatalog, we have point and multipoint, but not multipolyline or multipolygon for polyline and polygon.Why?
112738
I have 100 polygons in a GeoJSON file that partially overlap each other. I would like to produce 100 new polygons as follows:   The area covered by any of the original 100. This is their union. The area covered by at least two of the original 100. ... The area covered by all but one of the original 100. The area covered by all of the original 100. This is their intersection.   (I'm actually going to only keep 5-10 of these 100 results, but I expect the process for generating all 100 of them is the same as generating a subset of them)  What software / functions can I use to do this?    One approach I've already encountered in another similar project involves rasterizing all of the original polygons, then counting the overlapping pixels and producing new polygons from that data. This approach loses precision earlier than I would like to (I want to maintain near perfect precision up until the end of the process, THEN simplify things for display).    I could do this semi-manually with hundreds of union and intersection operations. This approach is not ideal because I want to re-run this process at intervals in the future as the dataset grows.
49951
I have two GeoDataFrames: one with 191k address points and another with 18 polygons representing catchment areas for specific schools. Theoretically, every address should fall into one of the zones. When running my code, I get the following error: ValueError: Length of values (191888) does not match length of index (191921)  I suspect that there are 33 points that are not matched to a polygon. import geopandas as gpd import os  from shapely.geometry import Point, Polygon   pointpath = &quot;/path/to/address points/&quot; point_df = gpd.read_file(os.path.join(pointpath,&quot;addresses.shp&quot;))   shapepath = &quot;/path/to/catchment areas/&quot; shape_df = gpd.read_file(os.path.join(shapepath,&quot;catchments.shp&quot;))   school_list = [] for i in range(len(point_df)):     pt = Point(point_df['geometry'][i])     for index, row in shape_df.iterrows():         poly = Polygon(row['geometry'])         if(pt.within(poly)):             school_list.append(row['school_name'])             print(i) point_df['zoned school']=school_list point_df.to_excel(os.path.join(pointpath,'foo.xlsx'))  First off, is this the most efficient way of performing this task? Second, is there a way to loop through the catchment areas and if there is no match, enter something like &quot;no match found&quot; so that the number of list items matches the number of dataframe rows?
15784
I'm creating a map with two shapefiles:   A polygon of counties Points of cities   I used the function Intersect to group the cities in each county.  I'm trying to get the number of cities in each county to show up in the legend.    For example, in county A there are 16 cities, in county B there are 7 cities and so on.  I'm trying to create a choropleth map that shows the number of cities in each county.
84377
I'm trying to figure out how to create a polygon that connects all the endpoints of a shapefile containing a set of polyilnes with pythonscript in ArcGIS, I'm having trouble doing this as the order of the nodes in the polygon is important. I want to achieve the grey polygon in the picture from the green lines
90101
I have a polygon shape file that has many overlapping features. Each feature represents an area used by polar bears. So some of the polygons overlap and some don't, and there are separate clusters of overlapping areas.   I would like to get a measure of how much overlap there is in a particular area. But I have no clue how to do this. I'm pretty new to GIS and am still learning the ropes, it just seems I can't find an answer.
18408
Does the shapefile support mixed geometry types (ie. point and polygon all in the same file)?
25698
I have a shapefile of thousands of polygon features, that i would like to break up into smaller pieces (i.e. break a square into 8 equal pieces). I have read all over these boards for the right solution and haven't found one yet unfortunately. I've tried parcel editor but that only allows you to manually edit one feature at a time, and I've tried fishnet but that doesn't run through each individual feature it just processes across the entire extent of the shapefile. I have the full license for ArcGIS so all options are game. Ultimately I would like to be able to split this initial shapefile of features into a specified amount of equal width slots that each would be their own feature in the resulting shapefile.  Any thoughts?
86383
I have a big Shapefile with 200,000 polygons but the file is too big for the application that will use it. I would like to generalise these polygons and create much smaller file.  I have tried to do this in QGIS using "Simplify Geometries" tool. I have tried this on a very small portion of my Shapefile and I am happy with the results but have small problem which I do not know how to solve.  I have appended the image to show the problem.  WHITE boundaries are boundaries before simplification. RED boundaries are after simplification. The problem areas are circled with orange colour. As you can see "simplified boundaries" contain some areas that after simplification do not belong to any of the previous polygons.  How do I simplify this Shapefile and keep common boundaries between polygons as a single line and eliminate areas that have been created after simplification?    ADDITIONAL INFORMATION:  After following suggested instructions    Convert polygons to lines  Simplify lines Convert lines back to polygons    I get the following results. It is slightly better than before but still I get areas outside original polygons (see white areas in the picture below).  @Andrew suggested that I associate each line with adjacent polygon but I do not know how to do it in QGIS.      I am still trying to complete simplifying polygons process. I have followed instructions suggested in this post and when I thought I got acceptable results one more problem appeared. Below is the summary of what I did with images of results. All steps have been performed using PROCESSING toolbox in QGIS.   First, I converted polygons to lines Second, I cleaned lines using v.clean with break option. This resulted in CLEANED VECTOR LAYER and ERROR LAYER. Error Layer (green dots on the provided image) has green dot on every line intersection. I do not know what this means. Third, I simplified lines using "SIMPLIFY GEOMETRY" tool (result in red lines in the images). Comparing simplified red lines and original orange lines I am happy with the result. Fourth, I wanted to convert lines back to polygons using "Polygonize" tool in "PROCESSING" and got results that I did not expect (second image with a shaded dark olive colour polygons). It looks like polygonizer connected error layer intersections and created completely different set of polygons ignoring simplified lines.   Could someone explain what went wrong here?   Why red simplified lines were not converted properly to simplified polygons?   As you can see I am not an GIS expert but need to do this myself. I do not know if I am too far from the solution but it is frustrating that I can see simplified lines that I found acceptable for what I'd like to do but cannot convert them to polygons.  Here are two images with results of last two steps of the process: