83 votes
Accepted

Reading shapefile in Python

read your shapefile with Fiona, PyShp, ogr or ...using the geo_interface protocol (GeoJSON): with Fiona import fiona shape = fiona.open("my_shapefile.shp") print shape.schema {'geometry': ...
user avatar
  • 50.7k
56 votes

Reading shapefile in Python

I find GeoPandas as the best performer here. import geopandas as gpd shapefile = gpd.read_file("shapefile.shp") print(shapefile)
user avatar
49 votes
Accepted

How to polygonize raster to shapely polygons

Use rasterio of Sean Gillies. It can be easily combined with Fiona (read and write shapefiles) and shapely of the same author. In the script rasterio_polygonize.py the beginning is import rasterio ...
user avatar
  • 50.7k
40 votes
Accepted

how to take cell size from raster using python or GDAL or RASTERIO

With PyQGIS ras = QgsRasterLayer("raster.tif") pixelSizeX= ras.rasterUnitsPerPixelX() pixelSizeY = ras.rasterUnitsPerPixelY() print pixelSizeX 2.11668210081 print pixelSizeY 2.11685012701 With GDAL ...
user avatar
  • 50.7k
34 votes
Accepted

Rasterize a shapefile with Geopandas or fiona - python

You are on the right track and the geopandas GeoDataFrame is a good choice for rasterization over Fiona. Fiona is a great toolset, but I think that the DataFrame is better suited to shapefiles and ...
user avatar
28 votes
Accepted

Import error: no module named _gdal_array

Make sure you have numpy installed before you attempt to install the GDAL Python bindings; without numpy, it appears the _gdal_array native code will not be installed. If you ended up in this ...
user avatar
20 votes

Raster reclassify using python, gdal and numpy

Instead of doing the reclassification as a double for loop described by dmh126, do it using np.where: # reclassification lista[np.where( lista < 200 )] = 1 lista[np.where((200 < lista) &...
user avatar
  • 886
15 votes

Zooming to layer extent in PyQGIS?

Something like below should work. vLayer = iface.activeLayer() canvas = iface.mapCanvas() extent = vLayer.extent() canvas.setExtent(extent)
user avatar
  • 6,974
12 votes
Accepted

How I can reverse numbers in a string without reversing any text?

Something like this should work: def reverse(s): items = s.split() digs = ''.join(i for i in s if i.isdigit()) dr = digs[::-1] return ' '.join(map(None, items)).replace(digs, dr) >...
user avatar
  • 8,354
11 votes
Accepted

Rasterizing shapefiles with GDAL and Python?

I tried out your code, slightly modified by me for adapting it to mi data (adding your 'hedgerow' field to my shapefile), and it ran well with only add to your code the line: target_ds = None. from ...
user avatar
  • 25.8k
10 votes

Use psycopg2 to do loop in postgresql

For one thing, you should generally avoid explicit looping like that in Python whenever possible. Psycopg2's cursor objects support the iterator protocol. This means you can iterate row by row over ...
user avatar
10 votes
Accepted

How to add vertex to an existing polyline programatically?

First case: insert new polyline You have to define the Polyline like so: pLine = [QgsPoint(1,1), QgsPoint(2,1), QgsPoint(2,2)] it is a list-of-QgsPoint. After you can put more QgsPoint into the ...
user avatar
  • 1,851
10 votes

Rasterize a shapefile with Geopandas or fiona - python

geocube is a new tool specifically designed for rasterizing geopandas data that wraps rasterio. It simplifies the process and eliminates the need for a template raster. https://github.com/corteva/...
user avatar
  • 5,607
10 votes

Making ArcPy interactive?

Python window is not an equivalent of the Python shell; hence, you won't be able to use the raw_input there. To implement the interactivity with the user, you may choose any of these alternatives: ...
user avatar
10 votes
Accepted

Copy attributes from existing shapefile to new shapefile (Python 2.7.13, GDAL)

1) With ogr, see Fast tip: Filtering features using OGR Python for example from osgeo import ogr from os import remove in_file= "shapefileA.shp" out_file = "shapefileB.shp" in_ds = ogr.Open( in_file )...
user avatar
  • 50.7k
9 votes
Accepted

Reading zipped ESRI BIL files with Python

Ok, I'm sorry to post a question and then answer it myself so quickly, but I found a nice set of course slides from Utah State University that has a lecture on opening raster image data with GDAL. For ...
user avatar
9 votes

Raster reclassify using python, gdal and numpy

Here's a basic example using rasterio and numpy: import rasterio as rio import numpy as np with rio.open('~/rasterio/tests/data/rgb1.tif') as src: # Read the raster into a (rows, cols, depth) ...
user avatar
  • 91
9 votes

Converting between coordinate systems for LAS file using LASPY

You should check what the scale and offset are for your file. This can be done as follows: van_taken.header.scale van_taken.header.offset This almost looks like an overflow error to me. The lower ...
user avatar
9 votes
Accepted

Error using pip install for arcpy: "Could not find a version that satisfies the requirement arcpy...."

arcpy ships with Esri's ArcGIS software package. It is neither free nor open source and, even if you were able to obtain it without an ArcGIS license, you would not be able to use it as it has a built-...
user avatar
  • 8,020
8 votes
Accepted

Arcpy Update Cursor (arcpy.da.UpdateCursor()) not saving changes to 'SHAPE@LENGTH'

In cursors, length is a read-only property. I couldn't imagine what a predictable outcome would be for setting a new length of a line. Would it just extend the last point out in the bearing from the ...
user avatar
8 votes
Accepted

How to create a polygon feature class from polylines in Python ArcGIS?

You need to break it down to points if they're good points and reconstruct. Polylines are made from paths, polygons are made from rings. Although they are created in a similar way they are not ...
user avatar
8 votes
Accepted

Permanently add a python toolbox to ArcToolbox

This help topic should get you started -- basically you embed your toolbox in a Python package and install it in your local Python installation. Then your tool should show up automatically under ...
user avatar
8 votes

How to count point shp inside polygon shp using Python?

The following approach uses a Search Cursor and Python dictionary to perform the following workflow: Select points within each polygon feature Update dictionary with key (OID) and value (point count) ...
user avatar
  • 50.2k
8 votes
Accepted

How to count point shp inside polygon shp using Python?

I can crush this down to 3 lines of code, no cursors required! import arcpy arcpy.SpatialJoin_analysis("Site", "points","in_memory/points_SpatialJoin", "JOIN_ONE_TO_MANY", "KEEP_ALL", "", "INTERSECT")...
user avatar
  • 38.4k
8 votes

How to polygonize raster to shapely polygons

Here is my implementation. from osgeo import ogr, gdal, osr from osgeo.gdalnumeric import * from osgeo.gdalconst import * import fiona from shapely.geometry import shape import rasterio.features #...
user avatar
8 votes
Accepted

" ".join(list) not inserting spaces when calculating field

If you want to use the Calculate Field tool (instead of an Update Cursor), what you're assigning to val needs to be an unevaluated python expression. That is, it needs to be identical to the string ...
user avatar
  • 8,020
8 votes

SQL queries in PostGIS database layer using Python and QGIS

Adding PostGIS table to a QGIS map In a QGIS plugin I would use QgsDataSourceURI from the pyqgis API. Here is some snippet form a project I worked on. Database connection is wrapped in a function. ...
user avatar
  • 7,291
8 votes
Accepted

Saving python Rtree spatial index to file?

Is the built-in disk serialization an acceptable solution? Make an index and flush it to disk: from rtree.index import Index idx = Index('filename') idx.insert(0, (1, 2, 3, 4)) idx.get_bounds() # [1....
user avatar
  • 3,857
8 votes
Accepted

python GDAL 'GetDriverByName', argument 1 of type 'char const *'

Because you imported unicode_literals, you're passing a unicode literal to GDAL which is expecting a string literal. So, explicitly cast the 'GTiff' arg to a str. E.g. >>> from ...
user avatar
  • 51.7k
7 votes
Accepted

Increasing speed of Python scripts using arcpy

I have wanted to comment first, but then it seemed more appropriate to wrap it to be an answer (even though it might be incomplete). I've run your code on my machine (top hardware laptop with SSD) ...
user avatar

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