Skip to main content
66 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)
Mobasshir Bhuiya's user avatar
48 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 ...
gene's user avatar
  • 55.1k
36 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 ...
Marciano Saraiva's user avatar
13 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/...
snowman2's user avatar
  • 7,459
11 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) ...
Damon's user avatar
  • 111
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 ...
xunilk's user avatar
  • 30k
11 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 )...
gene's user avatar
  • 55.1k
9 votes

Raster reclassify using python, gdal and numpy

Just to complete the answer from @Mattijn, I think that will lead into a problem if the input classes overlap with the output classes. I don't want my new value to be changed by the next rule. I don'...
etrimaille's user avatar
  • 7,290
8 votes
Accepted

How to iterate through all fields, and all records in each field with GDAL/OGR

The reason for this behavior is that ogr reads the features of layer sequentially and updates the "read position" each time. After reading through layer once, the "read position" is at the end of the ...
Logan Byers's user avatar
  • 2,859
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. ...
Jakob's user avatar
  • 7,491
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....
Marc Pfister's user avatar
  • 4,097
8 votes
Accepted

Using tempfiles for intermediate dataset in ArcPy?

You cant have a file extension for rasters in the in_memory workspace so change slope = "in_memory/slope.tif" to slope = "in_memory/slope" See: 001167: No extension is allowed for in-memory raster ...
Bera's user avatar
  • 74.8k
8 votes
Accepted

Creating QGIS copy-paste features between two layers using PyQGIS?

To copy all features; create a list, get features from source layer, create data provider on destination layer, and finally add features to destination layer: sourceLYR = QgsMapLayerRegistry.instance(...
artwork21's user avatar
  • 35.1k
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 ...
user2856's user avatar
  • 67.2k
7 votes

Import shapefile is not working in pyshp?

Try pip install pyshp in your command prompt before trying to run import shapefile.
Jimmy Feterman's user avatar
7 votes

Using ArcPy on MacBook?

ArcPy is a site package bound to a release of Python associated with ArcGIS Desktop (Windows -- 32-bit or 64-bit, with Background Geoprocessing installed) or ArcGIS Server (Windows and Linux -- 64-bit)...
Vince's user avatar
  • 20.2k
7 votes

RTree spatial index does not result in faster intersection computation

My answer is essentially based on another answer by @gene here: More Efficient Spatial join in Python without QGIS, ArcGIS, PostGIS, etc He proposed the same solution using two differents methods, ...
mgri's user avatar
  • 16.3k
7 votes
Accepted

Catching arcgisscripting.ExecuteError and error details?

I suspect what you actually want to catch is an arcpy.ExecuteError (or have you imported arcgisscripting somewhere in your code?) except arcpy.ExecuteError: print arcpy.GetMessages() # Handle ...
Midavalo's user avatar
  • 29.8k
7 votes
Accepted

Why does osr.SpatialReference return different values in python2 and 3?

The projections differ in the datum shift values for the conversion from Amersfoort datum to WGS84. The first one is tfm code 4833, and the second is tfm code 15934. GDAL 2.1.0 uses tfm code 4833, ...
AndreJ's user avatar
  • 76.7k
6 votes

Reading/writing utf-8 encoded data using Fiona?

Fiona read ok utf-8 files without add nothing. Try encoding='utf-8' only when output with fiona. So change... with fiona.open(out_file, 'w', **meta) as output: To with fiona.open(out_file, 'w', ...
Juanma Font's user avatar
6 votes

Import error: no module named _gdal_array

Things are a little different in 2023, since build isolation was introduced. Pip will now build packages prior to installation within an isolated Python environment, so even if numpy is installed in ...
joerick's user avatar
  • 161
6 votes
Accepted

It is possible to get single polygon using gdal.Polygonize()?

From the documentation: The algorithm will generally produce very dense polygon geometries, with edges that follow exactly on pixel boundaries for all non-interior pixels. For non-thematic ...
user2856's user avatar
  • 67.2k
6 votes
Accepted

Testing uppercase vs lowercase field values on the fly using ArcPy & Python?

From the ArcGIS help topic "SQL reference for query expressions used in ArcGIS": Strings are case sensitive in expressions. For feature classes and tables, you can use the UPPER or LOWER function ...
Bjorn's user avatar
  • 2,609
6 votes
Accepted

How to efficiently determine which of thousands of polygons intersect with a linestring

It is a much easier if you directly compute the shapely geometries (shape()): import fiona from shapely.geometry import LineString, Polygon, MultiPolygon, shape # Open each layer poly_layer = ...
gene's user avatar
  • 55.1k
6 votes
Accepted

How to use OGR Simplify in Python

If you look at the link you provided, you will see that Simplify is a method of the OGRGeometry class. In Python, Simplify is a method (member-function) of ogr.Geometry. OGRGeometry * OGRGeometry::...
Logan Byers's user avatar
  • 2,859
6 votes
Accepted

No "committedFeaturesAdded" signal after dataProvider().addFeatures() - QGiS 2.14.8

According to one of the QGIS developers (@MatthiasKuhn) in his website OPENGIS.ch, he suggests to completely avoid dataProvider() methods as he lists the following (emphasis mine): You cannot undo ...
Joseph's user avatar
  • 76k
6 votes
Accepted

SQL queries in PostGIS database layer using Python and QGIS

If conn is your databse connection from your code above, you fire your sql-statement as follows: c = conn.cursor() c.execute('SELECT * FROM mytesttable') c.fetchall() Where fetchall() returns a list ...
Jochen Schwarze's user avatar
6 votes

Getting attribute value from vector layer after mouse click in PyQGIS?

What you are trying to do is identify a feature of a particular layer and then get a value of a specific attribute. To do that you will need to use the QgsMapToolIdentify which allows you to identify ...
Chiller's user avatar
  • 226
6 votes
Accepted

How to import multiple python scripts in one script tool

No, you cannot import multiple scripts. The script tools have been originally designed to be based on a single Python without considering users writing multimodular Python tools. The option to zip ...
Alex Tereshenkov's user avatar
6 votes
Accepted

arcpy DLL load failed in standalone script

You can install 64-bit Background Geoprocessing. This will install the 64-bit python, and a version of arcpy that will run with the 64-bit python. Note that not all arcpy tools work in 64-bit: ...
Midavalo's user avatar
  • 29.8k

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