Hot answers tagged

23

EDIT: 2015 Solution My solution now is to use a small 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 ...


18

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 ...


13

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 ...


12

use QgsMapLayer::loadNamedStyle uri = "/home/user/style.qml" layer.loadNamedStyle(uri)


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 ...


9

You're doing your installation wrong. Instead of pip install shapely use the Windows installer available at https://pypi.python.org/pypi/Shapely#downloads And click on the file Shapely-1.2.17.win-amd64-py2.7.exe Launch the install and it will be OK after. Just as an information, "pip install shapely" works when you have the C compiler installed to ...


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

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 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 case x, y, and z properties need to re-scale and re-offset the coordinates to store it as an integer (which is how LAS files store them). To be honest, setting ...


8

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 you would type into the Calculate Field tool if you were using the GUI version. What you're currently assigning to val is "!FEDIRP! !FENAME! !FETYPE!". Any of ...


8

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 ...


7

If you add a geoprocessing tool to a toolbar it will run immediately upon clicking it, provided it has no parameters:


7

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 ...


7

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 = ...


7

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.


6

>>>'R12345678910'[1:] '12345678910' Edit Appending [1:] to a string in python will remove the initial character. Look up slice in the python help. To use this in the ArcGIS field calculator, you will need to turn on Python parsing for the unitCode = enter !your_field_name![1:]


6

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 ...


6

It looks like you are missing another zone = cursor.next() within the While loop You need to increment the cursor to the next feature after you're done with it or the loop starts over on the same feature. incidents = r"c:\users\documents\arcgis\arcgis tutorials\psu tutorials\project3\policedata.gdb\GraffitiIncidents" patrol_zones = ...


6

As already been mentioned in GS exchange, the QGIS version of Kyng Chaos uses the standard Apple Python and the version 2.x (and not the 3.x, nor others Python implementation, Homebrew, Anaconda, etc.) As indicated in the documentation, you must first add PyQGIS to the PYTHONPATH I use here the Terminal application: export ...


6

You can set the value of the parameter to the values you want to be checked, at least when using a Python Toolbox. The same should be true for your case. For example: def getParameterInfo(self): p = arcpy.Parameter() p.datatype = 'String' p.multiValue = True p.name = 'test' p.displayName = 'Test' p.parameterType = 'Required' ...


6

1) 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': ...


6

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: ...


6

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.


6

in provides a quick logical test for determining if a value is contained in a list, dict, or string. if from_g in dct_max: either from_g is found in dct_max (true) or it's not (false). The rest of your questions would be resolved by researching how dict objects work (lots of good examples on Stack Overflow).


5

Based on your results, it looks like field1 may have a space (" ") in the field, instead of an empty string. def concat_fields(field1, field2): if field1.strip() == "" or field2.strip() == "": return "" else: return field1 + field2


5

Did you check this page? It may give you some idea how to set it up: http://grasswiki.osgeo.org/wiki/GRASS_and_Python -> Creating Python scripts that call GRASS functionality from outside --> MS-Windows


5

First make sure you have the 32 bit PyScripter installed, not the 64 bit. Then in Tools -> Python Path make sure you have PyScripter pointing to the following paths: C:\Program Files (x86)\PyScripter\Lib\rpyc.zip C:\Windows\system32\python27.zip C:\Python27\ArcGIS10.2\DLLs C:\Python27\ArcGIS10.2\lib C:\Python27\ArcGIS10.2\lib\plat-win ...


5

getClass (In , Out , Therid, freq ) if FREQUENCY== 1: return str(In) elif FREQUENCY== 2: return (str(In) + "-" + str(Out) ) elif FREQUENCY == 3: return (str(In) +"-" + str(Out) + "-" + str(Therid) ) else: return "other frequency" here is a quick fix. Concantenation in Python uses "+", and I converted ...


5

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 ...


5

With cursors and the csv module, this should go pretty quick: import arcpy, csv, time arcpy.env.workspace = <path to gdb> table_list = arcpy.ListTables() csv_out = <path to csv> #Get name of fields from first entry fields = [x.name for x in arcpy.ListFields(table_list[0])] start = time.time() counter = 0 with open(csv_out, "wb") as f: ...



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