Tag Info

New answers tagged

1

I'm using OSGeo.GDAL for this code. It is extracted from my own working code but is incomplete, it will show you the basics of opening and reading a raster using GDAL. The source for GDAL is downloadable, there is mostly C and C++ but some python... no C# that I know of - C# is windows only, GDAL is multi-platform. Many times I have referred to the source ...


0

Loop through geodatabase (to get list of feature classes) Use Walk (arcpy.da) method Once you have the feature class you may want to verify data type (feature class, table,....etc) before you start the list field loop. To do this you may use the Describe Object property dataType. For checking data type you may reference this Q/A: Check layer data type ...


1

The SSDataObject allows for a wide array of spatial references, with a lot of linear/angular units, but it is sometimes possible for a spatial reference to have a linear/angular unit that is not in the known list. That is what is happening here: 'M' is not a known linear unit. The quick solution is to project your data to a known spatial reference. You ...


5

I see in your script you are using arcpy, in which case you you can use the out-of-the-box Table to Table (Conversion). This tool also allows you the freedom to select which fields to include as FieldMappings as well as directly outputting a .csv file. import arcpy fc = r'C:\path\to\your\fc' outws = r'C:\temp' arcpy.TableToTable_conversion (fc, outws, ...


1

FWTools provides supposedly easy-t-use wrappers for a lot of the GDAL functions. Once upon a time FWTools was THE defacto place to go and get your GDAL binaries, but not anymore. Personally I think the Python API for GDAL/OGR is already easy enough for scripting and FWTools is a bit redundant (though it gives some nice convenient utilities in QGIS - so has ...


0

Solved it. When I was creating my new zip/kmz my code was creating various folders within the zip/kmz. Changed: NewZip.write(addedfile) to: NewZip.write(addedfile, newfl)


3

In the looong list of types there is GPValueTable which has an example here: def getParameterInfo(self): param0 = arcpy.Parameter( displayName='Input Features', name='in_features', datatype='GPValueTable', parameterType='Required', direction='Input') param0.columns = [['Feature Layer', 'Features'], ['Long', ...


3

In addition to the answers about changing your cursor and reducing the number of them, you can also parallelise this a little by using subprocesses. Subprocesses in Python get around the limitation of the Global Interpreter Lock (GIL) - as opposed to multithreading in Python (a different thing to multiprocessing). Although ArcGIS 10 uses multiprocessing ...


1

In addition to the above suggestions, I would also suggest to use list comprehensions for simple loops. For example: rows = arcpy.SearchCursor(OL_FC) for row in rows: x = row.getValue("LENGTH") lengths.append(x) Change to: lengths = [row.getValue("LENGTH") for row in arcpy.SearchCursor(OL_FC)]


3

Try replacing this line: pUnk_line = pFact.Create(CLSID(esriGeometry.Line)) with this: pUnk_line = pFact.Create(CLSID(esriGeometry.Polyline)) In the help on LineElementClass is says right at the bottom: Geometry: LineElement accepts geometry of type esriGeometryPolyline. The Polyline is used as the geometry with which the symbol is drawn.


7

In addition to using the new arcpy.da cursor, I would also suggest: You have many different search cursors on the same layer, see if you can eliminate some of those and pull your attributes from one or two Apply an Add Attribute Index on any column that you are querying against See if you can remove the select layer by attribute logic and apply that query ...


0

Switch over to arcpy.da for all of your cursors. The old arcpy cursor objects broke at 10.1 sp2 and the only way ESRI could fix it was to create the new arcpy.da cursor objects. I had a process that ran in 10.1 sp1 that took 18 hours using the old cursor objects. After sp2 it took over 12 days before I killed it. The new arcpy.da cursors takes 4 hours. ...


3

You need to create raster objects when working with many of the spatial analyst tools, including Con (Spatial Analyst). Try the following changes: import arcpy from arcpy.sa import * arcpy.env.overwriteOutput = True arcpy.env.workspace = r"D:\Projekt\Testprojekt\Daten\Ergebnisse" arcpy.CheckOutExtension("Spatial") remaped2 = Raster("remaped2.img") slope = ...


0

You can import your shapefile to a postgis database with this python command : import os #Import shapefile to postgis DB os.system("shp2pgsql -s SRID -c -D -I /path/shape.shp tablename | psql -d dbname -h localhost -U username") (Just change : SRID (ex 4326), tablename (give any name), path, dbname and username).


0

Use the arcpy.List... functions. First have to set the env.workspace to the fgdb. Then use arcpy.ListTables() or arcpy.ListFeatureclasses(). Each of these returns a python list of the requested type. If the list is empty (len(list) == 0), then there is no thing of that type. Unfortunately there does not seem to be a higher level function like ...


4

You may use Describe Object property dataType: desc = arcpy.Describe("C:/base.gdb/test") if desc.dataType == 'FeatureClass': print 'fc' elif desc.dataType == 'Table': print 'table' else: print desc.dataType


0

It may not be the cause but its good practise to check out the spatial extension and then check it back in at the end of your code. So after the line from arcpy.sa import * put arcpy.CheckOutExtension("Spatial") then at the end of your code use: arcpy.CheckInExtension("Spatial") If you look closely at the error message its trying to create an output ...


1

I think that when you iterate over features in a gdal layer you're using OGRLayer::GetNextFeature() so after you iterated over all features, next feature will always be empty. That explains why you get your expected result when you call driver.Open(file, 0) inside the loop. You can use OGRLayer::ResetReading() to start from the top On the other hand, ...


1

Ran into the same error when trying to upgrade my GDAL from 1.9.0 to 1.11.0. Looks like on some Linux systems, there is some sort of library caching that can interfere. Doing the following: export LD_PRELOAD=$THEPREFIXPATH/lib/libgdal.so.1 or for bash environments: LD_PRELOAD $THEPREFIXPATH/lib/libgdal.so.1 was all I needed (substituting what ever you ...


11

One of the developers of arcpy.da here. We got the performance where it is because performance was our primary concern: the main gripe with the old cursors were that they were slow, not that they lacked any particular functionality. The code uses the same underlying ArcObjects available in ArcGIS since 8.x (the CPython implementation of the search cursor, ...


1

Performance related Cursor only iterates through set list of fields by default (not the entire database) Other not directly related to performance, but nice enhancements: Ability to use tokens (e.g. SHAPE@LENGTH, SHAPE@XY) for accessing feature geometry Ability to walk through databases (using arcpy.da.Walk method)


0

@James Hi James Keen to find out if you came write with the following. I'm busy with my Masters Thesis and Looking to multiprocess the Arc Hydro Terrain Preprocessing steps that use the same tools that can be found under Spatial Analyst Tools Hydrology.


1

I just ran into a similar problem and used the idea here to tell Python that my layers are rasters using Raster(). However, I did this not in the Con() function itself, but rather before that, when specifying the in_conditional raster, in_true_raster and in_false raster. E.g., inRaster1 = Raster("mydata1") inRaster2 = Raster("mydata2") outCon = ...


0

I'm writing a pyqgis 2.2 plugin with qgis 2.2 I succeeded in accessing and displaying vector data (geometries & attributes). I succeed also to create a 'beforecomitechanges' signal ( emitted, before changes are commited to the data provider). Thus a message has appeared into qgis logwindow ("comit change" label) after editing operations and before ...


1

Instead of 'print radius' put in a 'print whereClause' and post the output from that, that's a lot easier to check than having to manually decipher the format string. Furthermore, I'm not sure the triple-quote and named argument formatting is helping legibility much - I'd suggest "'NEAR_DIST' <= '{0}' AND ".format(radius, y, z) ; much easier to read, ...


0

Thanks those who spent their endevour. I have been able to solve the problem. My modified code is as below feature = "C:\Users\Bakul\Desktop\Od\example_shapefile\Polyline_segments_example.shp" radius = 500 # create a dictionary to hold the list of near ids for each input id nearest_dict = dict() arra = [] whereClause='''"NEAR_DIST" ...


0

I see this as two questions: 1) How to find, merge and dissolve features that meet your date requirements and 2) How to preserve the attributes of the search date feature. I will address question 1 in detail. There are several ways to approach this: using Select Layer By Attributes (Data Management) or with a SearchCursor. I often prefer to use the ...


2

With respect to your comment: "Is there a way to analyze and catch the errors in the code itself?" Use arcpy.mapping.AnalyzeForSD(path_to_sddraft) to get a Python dictionary of your errors, warnings and messages. Refer to the AnalyzeForSD (arcpy.mapping) help for code samples and further explanation.


4

You are using the syntax from the question, not the answer. Also, the pre-logic code for Python can't reference field names. You also might want to check out .rpartition(). You shouldn't have to use pre-logic at all: Sector = !FolderPath!.rsplit("/")[0] But if you did want to use pre-logic, here's how to do it: def sect(field): return ...


2

Here is a general python script that will compare pre and post lengths and create the >30% select feature class (make sure your line layer has a unique ID column to base the join field method on): import arcpy arcpy.env.workspace = 'C:/Temp/test.gdb' arcpy.Intersect_analysis(["line", "AOI_polygon"], "line_intersect", "ALL", "", "") ...


1

Sounds like a lot of data to process. Make sure your data is in a File GeoDatabase which will ensure there is a spatial index. Without knowing your data I do not know how long your lines are, so if they extend across many of your polygons then consider using the SPLIT tool to improve the efficiency of the spatial index. So what are these polygons, ward ...


1

The Java Topology Suite includes a TopologyPreservingSimplifier. The code does not include a reference for the implementation, beyond stating that it operates in a similar manner to Douglas-Peucker, with additional constraints on altering the topology. This functionality has made it into the Java-to-C++ translation of JTS, libgeos, which is further ...


0

The best answer I have for this (to my own question), is to continuously save to a raster file, overwriting it. You then use another program to continuously read from that same file over and over again. If all parts of this thing worked properly it would be something close to graphical animation.


0

The two GIS web mapping terms you are describing are indeed clustering and then spatial indexing. Clustering is usually done client side while indexing is done server side, usually using a geodatabase, with a server-side map rendering engine in the middle. In KML, there is a relatively new feature called "Regions" which tries to handle the display side of ...


1

The ETOPO1 dataset merges topography and bathymetry in one elevation model. Quoting the home page: ETOPO1 is a 1 arc-minute global relief model of Earth's surface that integrates land topography and ocean bathymetry. It was built from numerous global and regional data sets, and is available in "Ice Surface" (top of Antarctic and Greenland ice ...


7

First, install the psycopg2 package, a Pythonic interface for PostgreSQL. Then, use ST_MakePoint: >>> import psycopg2 >>> conn = psycopg2.connect(dbname=..., port=..., user=..., password=..., host=...) >>> x, y, z, = 32, 34, 0 >>> cur.execute("SELECT ST_SetSRID(ST_MakePoint(%s, %s, ...


1

My lib PyGeoj is specifically meant as a geojson file reader and writer, with a simple API that turns the file contents into objects with attributes, so you don't have to deal with the dictionaries directly. It also has some convenience methods, like calculate and add the bbox for the entire feature collection or just for each feature. So for instance, the ...


1

Try this while connecting: currentIndexChanged function pass 1 argument i.e is changed index and while defining build_Layer_Index_Changed pass two arguments (self, index). QtCore.QObject.connect(dlg2.Sel_Build_Layer, QtCore.SIGNAL("currentIndexChanged(int)"), self.build_Layer_Index_Changed())


0

I'm guessing the parameters are only relative to where the .py file exists. Maybe you could get the input parameters from a script tool form?


1

In a command window, type set > set.txt to get a list of all environment variables you have set. Your python installation may have set some values that QGIS does not like. The PATH variable is save, because qgis.bat sets its own path variable, but PYTHONPATH or something else may be harmful. Once you found a link to C:\Python27, go to the system ...


2

See this prior answer. Each version of ArcGIS uses a specific version and architecture of Python and is hard-linked against it. Forcing an ArcObjects application to use an incompatible Python version will likely lead to a crash.


0

QgsVectorLayer.changeGeometry function can be used to update the geometry after combining the manipulated geometries to form a single geometry. if geom.isMultipart(): geomColl = geom.asGeometryCollection() tempGeom = QgsGeometry() for g in geomColl: #g is QgsGeometry g2 = reverseDirection(g) # your function to manipulate the geometry ...


0

OK so you want to know how to generate polygons centered on selected points in pyQGIS and retain all the attributes of the points in the new polygons? Here's a script to do that: Note that the code was written to apply to a points-containing example shape file I have. You need to remove the section which reads in my example file in order for it to use your ...


1

How about something like this: import arcpy mainTbl = r"C:\test.gdb\main" lutTbl = r"C:\test.gdb\lut" #Note the order of the fields in the search cursor has to coincide with field order in the update cursor #Also assumes the matching fields are of compatibale types (exanple: can't insert string into integer) lutDict = {r[0]:[i for i in r[1:]] for r in ...


0

The documentation appears to be incorrect. Try using a colon instead of a dash, as in: --zoom=9:15


1

Test the arcpy.JSONToFeatures_conversion(jsonfile, outputshapefile) function.


0

In your examples you are tiling two different files. In the first xml it is "mar_apr.tif" and in the second "mar_apr_CLIP1.tif". Maybe this is the reason for the difference in the output - because your input files differs in fact as well? The old MapTiler made only color palette expansion and similar small modifications which should not affect the location ...


1

I modified the redistribute_selection() function above to make ~/.qgis2/python/mytools.py : from qgis.core import (QgsFeature, QgsGeometry, QgsVectorLayer, QgsMapLayerRegistry, QgsField) from PyQt4.QtCore import QVariant from qgis.utils import iface import math import numpy def ...


0

Building on @gene 's answer above if you're looking to approximate a curve as a sequence of points using spline interpolation. In Python you can do this through the scipy.interpolate library. Particularly 1d interpolation. For example import numpy as np import scipy.interpolate coords = np.array([[0, 0], [25, 10], [50, 50]]) #The curve fits as a ...


2

Try the following workflow: Reclassify your rasters so that Value = 1. Calculate Cell Statistics using a "SUM" statistic. Any value in the resulting raster > 1 is an overlap area. Additionally, the value of the resulting raster indicates how many overlapping rasters there are.



Top 50 recent answers are included