58
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': 'LineString', 'properties': OrderedDict([(u'FID', 'float:11')])}
#first feature of the shapefile
first = shape.next()
print first # (GeoJSON format)
{'geometry':...
48
See the OGR Projections tutorial and the OGRSpatialReference class. In particular, the GetAttrValue method.
Here's a worked example.
from osgeo import gdal,osr
ds=gdal.Open(r'SOMERASTER.TIF')
prj=ds.GetProjection()
print prj
srs=osr.SpatialReference(wkt=prj)
if srs.IsProjected:
print srs.GetAttrValue('projcs')
print srs.GetAttrValue('geogcs')
For my ...
42
Updated answer for Python 3
You should not nowadays encounter any issue while installing on Windows using (as long as pip is version 8 or more according to official Shapely doc and you are using Python 3):
pip install shapely
To check pip version, do :
python -c "import pip;print(pip.__version__)"
If you need to upgrade pip, just do :
pip install -U ...
37
I created a small (and relatively popular) module which goes off and hunts for ArcGIS on your PC. Once find it adds the correct paths to the environment so that you can import arcpy. The usage goes like this:
try:
import archook #The module which locates arcgis
archook.get_arcpy()
import arcpy
except ImportError:
# do whatever you do if ...
32
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
from rasterio.features import shapes
mask = None
with rasterio.Env():
with rasterio.open('a_raster') as src:
image = src.read(1) # first band
...
28
I find geopandas as the best performer here.
Code:
import geopandas as gpd
shapefile = gpd.read_file("shapefile.shp")
print(shapefile)
27
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 geometries than nested dictionaries.
import geopandas as gpd
import rasterio
from rasterio import features
Set up your filenames
shp_fn = '...
27
With PyQGIS
ras = QgsRasterLayer("raster.tif")
pixelSizeX= ras.rasterUnitsPerPixelX()
pixelSizeY = ras.rasterUnitsPerPixelY()
print pixelSizeX
2.11668210081
print pixelSizeY
2.11685012701
With GDAL
from osgeo import gdal
raster = gdal.Open('raster.tif')
gt =raster.GetGeoTransform()
print gt
(258012.37107330866, 2.11668210080698, 0.0, 163176.6385398821, 0....
20
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)
Starting with GeoPandas 0.3.0, you can use the provided x and y properties instead:
gdf["x"] = gdf.centroid.x
gdf["y"] = gdf.centroid.y
17
If an unhandled exception, such as an ImportError, occurs before the add-in classes are instantiated they will become unresponsive, be given a [Missing] label, and have a red symbol for their icon in the case of items on toolbars or in menus.
You can confirm whether an import error is happening by wrapping your import statement with an exception handler and ...
17
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 situation, removing gdal, installing numpy and then reinstalling gdal might help:
pip uninstall gdal
pip install numpy
pip install GDAL==$(gdal-config --...
16
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) & (lista < 400)) ] = 2
lista[np.where((400 < lista) & (lista < 600)) ] = 3
lista[np.where((600 < lista) & (lista < 800)) ] = 4
lista[np....
13
Leaving the rest below, but the main thing was accessing the geometry properly. If iterating over rows, e.g. for index, row in zones.iterrows(): you can simply use row.geometry.centroid.x and row.geometry.centroid.y. Geometry is a special column included in a GeoDataFrame, so every row has a geometry attribute.
You are accessing that attribute, which ...
12
Something like below should work.
vLayer = iface.activeLayer()
canvas = iface.mapCanvas()
extent = vLayer.extent()
canvas.setExtent(extent)
12
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)
>>> reverse('321 test')
'123 test'
@mnpeterson brought up a good point about assuming where the numbers are...My post above would string all digits ...
10
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 the results without needing to manually take care of indices.
Another thing is that you are calling the execute function many times inside that loop when it ...
10
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 list by append to insert the element at the end of the list:
pLine.append(QgsPoint(3,2))
or inserting some vertex point at a specific location of the list:
## ...
10
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:
build custom script tools with input parameters (via arcpy.GetParameterAsText());
build Python add-ins (which have text boxes to fill in);
use 3rd party Python ...
answered Apr 21 '16 at 16:22
Alex Tereshenkov
28.8k33 gold badges4444 silver badges109109 bronze badges
10
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 )
in_lyr = in_ds.GetLayerByIndex(0)
if exists(out_file):
remove(out_file)
driver_name = "ESRI Shapefile"
drv = ogr.GetDriverByName( driver_name )
out_ds = ...
9
The API docs state
Memory data providerType (memory)
The memory data provider is used to construct in memory data, for
example scratch data or data generated from spatial operations such as
contouring. There is no inherent persistent storage of the data. The
data source uri is constructed. The url specifies the geometry type
("point", "...
9
To iterate over the layers in the map, get a reference to the current map document and list the layers within it:
mxd = arcpy.mapping.MapDocument("CURRENT")
layers = arcpy.mapping.ListLayers(mxd):
for layer in layers:
# do something with 'layer'
To just get the number of selected features, try leveraging the Describe object's fidSet property:
desc = ...
9
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 the record, here is the code I used to open the PRISM Climate Group datasets (which are in the EHdr format).
def ReadBilFile(bil):
import gdal
gdal....
9
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) array,
# dstack this into a (depth, rows, cols) array,
# the sum along the last axis (~= grayscale)
grey = np.mean(np.dstack(src.read()), axis=2)
...
8
This sort of question is better answered in StackOverflow but the answer is straight-forward enough so I'll give you a hint here.
Your date is not a date as far as Python is concerned but a division sum - which is the main reason why it doesn't work. Your code also won't give you the last four digits. You need '[-4:]' (yours gives everything except the ...
8
You can actually deal with each part of a multipart polygon by creating a separate polygon object. Take a look at the following code.
import arcpy
from arcpy import env
env.workspace = "C:/Data/Exercise08"
fc = "Hawaii.shp"
for row in arcpy.da.SearchCursor(fc, ["OID@", "SHAPE@"]):
print("Feature {0}: ".format(row[0]))
partnum = 0
for part in ...
8
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 next to last point? What if it were multipart? Would it grow the entire polyline segment by segment?
8
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 compatable, hence your error.
Go through each point on the line adding a point to your output array and then insert.
here's a post that might help Get all the points ...
8
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 system toolboxes.
8
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) for each iteration
Find max point value and corresponding OID and write to a text file
import arcpy, os
points = r'C:\temp\mytest\points.shp'
polys = r'C:\...
8
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")
arcpy.Statistics_analysis("points_SpatialJoin", "in_memory/stats", "Join_Count SUM","Id")
Then simply sort the table to find the polygon with most points.
Only top voted, non community-wiki answers of a minimum length are eligible
Related Tags
python-2.7 × 688arcpy × 229
pyqgis × 144
python × 120
qgis × 98
gdal × 64
arcgis-desktop × 63
arcgis-10.1 × 56
arcgis-10.2 × 45
qgis-plugins × 44
qgis-2 × 28
arcmap × 25
shapely × 25
cursor × 21
raster × 20
ogr × 20
numpy × 19
installation × 18
shapefile × 16
grass × 14
coordinate-system × 13
arcgis-10.3 × 12
python-addin × 12
qgis-processing × 11
pyqt × 11